Consider the following class:
public class MyBean { private A a; @Autowired(required=true) public void setA(A a) { this.a = a; } public A getA() { return a; } }
There are times when it is necessary to redefine automatic injection, for example, when Spring cannot find one candidate for injection. In XML, I can give the following example:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="first" class="my.pkg.AImpl"/> <bean id="second" class="my.pkg.AImpl"/> <bean id="myBeanFirst" class="my.pkg.MyBean"> <property name="a" ref="first"/> </bean> <bean id="myBeanSecond" class="my.pkg.MyBean"> <property name="a" ref="second"/> </bean> </beans>
Is there a way to do the same with Java Config? The following does not work (and I understand why), because Spring tries to autwire the property after returning from the myBean method, and it does not work with NoUniqueBeanDefinitionException:
@Configuration public class MyConfig { @Bean public A first() { return new AImpl(); } @Bean public A second() { return new AImpl(); } @Bean public MyBean myBeanFirst(A first) { MyBean myBean = new MyBean(); myBean.setA(first); return myBean; } @Bean public MyBean myBeanSecond(A second) { MyBean myBean = new MyBean(); myBean.setA(first); return myBean; } }
To change the MyBean class is not always an option, for example, because it comes from an external library. Is this the case when I need to use XML configuration?
Thanks Andrea Polci
Update Thanks for the two solutions, so the tariff (injection by name and using @Primary), but they do not solve my use case, so I have to be more specific, I think.
In my case, the use of the MyBean class comes from an external library, so any change is not possible. I also need to have more than one instance of MyBean, each of which introduces different capabilities of interface A. I updated the code above to reflect this (both xml and java).
Is there any solution using java config? Can I Avoid Autocovering MyBean Dependence? (Only on beans of this class, and not completely disable auto-connect for each bean in context)
java spring spring-java-config
Andrea Polci
source share