How to add parameter to factory - factory method - bean in Spring?

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 introduced 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 get 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 configuration of bean1 or bean2?

+4
source share
1 answer

This can be achieved in a slightly different way:

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

Now you can use non-intuitive syntax, for example:

 <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, propA and propB will be used as arguments to the instance() method.

+10
source

Source: https://habr.com/ru/post/1398816/


All Articles