Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Spring Bean using FactoryMethod with variable arguments from Spring?

How can we create a bean using FactoryMethod with variable arguments.

 public class ConnectionFactoryClass {

    public static Connection composeConnection(final Property... properties) {
       ...
    }
 }

bean.xml

  <bean id="Connection"
    class="com.example.ConnectionFactoryClass"
    factory-method="composeConnection"
    scope="singleton">
    <constructor-arg ref="Driver"/>
    <constructor-arg ref="Pool"/>
  </bean>

Spring is giving me an error saying,

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Connection' defined in file [./beans.xml]: No matching factory method found: factory method 'composeConnection'

like image 872
restrictedinfinity Avatar asked Aug 02 '26 06:08

restrictedinfinity


1 Answers

Try the following:

<bean id="Connection"
    class="com.example.ConnectionFactoryClass"
    factory-method="composeConnection"
    scope="singleton">
    <constructor-arg> 
        <array>
        <bean ref="Driver" />
            <bean ref="Pool" />
        </array>
    </constructor-arg>
  </bean>

I think you are having a problem because the JVM turns a var arg params into an Object Array and you need to pass in a single paramater to the constructor which is the array of objects. I have not tried the above xml so I might have typos in it, but something like the above should work.

like image 79
ams Avatar answered Aug 04 '26 05:08

ams