【发布时间】:2014-03-14 21:34:36
【问题描述】:
考虑以下类:
public class MyBean {
private A a;
@Autowired(required=true)
public void setA(A a) {
this.a = a;
}
public A getA() {
return a;
}
}
在某些情况下需要覆盖自动装配的注入,例如当 Spring 无法找到注入的单个候选者时。在 XML 中,我可以有以下示例:
<?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>
有没有办法用 Java Config 做同样的事情?以下内容不起作用(我理解为什么),因为 Spring 在从 myBean 方法返回后尝试自动装配该属性,但它因 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;
}
}
修改 MyBean 类并不总是一种选择,例如因为它来自外部库。 这是我必须使用 XML 配置的情况吗?
谢谢, 安德烈亚·波尔奇
更新 感谢您提供两种解决方案(按名称注入和使用@Primary),但它们不能解决我的用例,所以我认为我需要更具体。
在我的用例中,MyBean 类来自外部库,因此无法对其进行任何更改。我还需要有多个 MyBean 实例,每个实例都注入不同的 A 接口实例。我已经更新了上面的代码以反映这一点(xml 和 java)。
有没有使用 java config 的解决方案?是否可以避免自动装配对 MyBean 的依赖? (仅在该类的 bean 上,不会为上下文中的每个 bean 完全禁用自动装配)
【问题讨论】:
-
否决这个问题的人能否解释一下原因?
标签: java spring spring-java-config