Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

spring

factory

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?

like image 411
plus- Avatar asked Dec 28 '22 05:12

plus-


1 Answers

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.

like image 167
Tomasz Nurkiewicz Avatar answered Dec 31 '22 12:12

Tomasz Nurkiewicz