Bean @ Default user in spring

I work with SpringFramework and Java. I use Spring xml files to define the architecture flow, as well as the beans that will be used in the Java part.

I have two beans of the same class in my XML file, but they have different arguments for the constructor:

<bean id="beanA" class="Class" > <constructor-arg><value>valueA1</value></constructor-arg> <constructor-arg><value>ValueA2</value></constructor-arg> </bean> <bean id="beanB" class="Class" > <constructor-arg><value>valueB1</value></constructor-arg> <constructor-arg><value>valueB2</value></constructor-arg>--> </bean> 

Is there a way to set one of beans by default for @Autowired from Java? And, when I want to use a custom bean, apply the @Qulifier("beanName") annotation.

+4
source share
2 answers

try the primary attribute e.g.

 <bean id="b1" class="test.B" /> <bean id="b2" class="test.B" /> <bean id="b3" class="test.B" primary="true" /> 

this ensures that the b3 bean is introduced here

 public class Test { @Autowired B b; ... 
+5
source

Finally, I used the following: I have setter ( setClassValue(Class classValue) ) in the java code for the class I want to use. Then I set the autowire-candidate property to false in the bean so that it will not be used by default:

 <bean id="beanA" class="Class" autowire-candidate="false"> <constructor-arg><value>valueA1</value></constructor-arg> <constructor-arg><value>valueA2</value></constructor-arg> </bean> <bean id="beanB" class="Class" > <constructor-arg><value>valueB1</value></constructor-arg> <constructor-arg><value>valueB2</value></constructor-arg> </bean> 

Then in the xml file, where I define the bean of the class, which will be the @Autowired Class , I use the java method setClassValue(Class classValue) as follows:

 <bean id="classThatAutowire" class="ClassThatAutowire" > <property name="classValue" ref="beanA" /> </bean> 

In Java code, yo will be @Autowired beanB , and then install beanA . This is not the best practice, but it works.

0
source

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


All Articles