Spring – How to add a param to a factory-method of a factory-bean in Spring

factoryspring

let's say I have a factory bean:

<bean id="myFactory" class="com.company.MyFactory" lazy-init="true">
  <property name="myProperty" ref="propA">
</bean>

Let's say propA is a bean injected by IOC used in the factory method. And I have 2 beans generated from this factory:

<bean id="bean1" factory-bean="myFactory" factory-method="instance"/>
<bean id="bean2" factory-bean="myFactory" factory-method="instance"/>

How can I make bean2 to use a different myProperty than bean1 without using a different factory method? Or, how can I pass propA as a parameter to the factory-method from the bean1 or bean2 configuration?

Best Answer

This can be achieved in a slightly different way:

class MyFactory {
    public Bean instance(MyProperty myProperty) {
        return //...
    }
}

Now you can use counterintuitive syntax like following:

<bean id="bean1" factory-bean="myFactory" factory-method="instance">
    <constructor-arg ref="propA"/>
</bean>
<bean id="bean2" factory-bean="myFactory" factory-method="instance">
    <constructor-arg ref="propB"/>
</bean>

Believe it or not but propA and propB will be used as instance() method arguments.

Related Topic