我正在从XML转向注释。
我有接口类型House和My ,以及类类型HouseImpl和MyImpl。Spring 将 MyImpl 实例注入到 MouseImpl 实例中,
public class HouseImpl implements House
private My my;
public My getMy2() {
return my;
}
@Autowired
public void setMy2(My my) {
this.my = my;
}
所以HouseImpl
的属性被称为 my2
.
在 Spring 配置文件中,
<context:annotation-config></context:annotation-config>
<bean
id="house"
class="....HouseImpl"
>
...
</bean>
<bean
id="my"
class="my.test.own.spring_book_annotations.MyImpl"
>
</bean>
<bean
id="my2"
class="my.test.own.spring_book_annotations.MyImpl2"
>
</bean>
如果配置是XML格式的,那么house
配置中有autowired="byName"
,并且没有@Autowired
注释,则注入Bean my2
,因为属性名称是my2
(setMy2
是方法)。但是当我们使用注释时,会注入 bean my
,因为setMy2
参数的名称是 my
.
我的问题是为什么 setter 函数上的@Autowired不查看属性名称。
当 @Autowired
用于 setter 并且有多个匹配类型时,容器将查看参数名称以查找要注入的 bean。在您的情况下,参数是 My my
,因此将注入my
bean。您可以将参数更改为 My my2
,或使用 @Qualifier("my2")
注入my2
Bean。
如果要使用字段名称,请将@Autowired
放在字段本身上以使用字段注入。
你的代码是这样的
@Autowired
public void setMy2(My my) {
this.my = my;
}
当你写注解@Autowired时,它会采用带有setXXX名称的bean。这里XXX是My2。
因此,注入了带有my2
id 的 bean。为了将带有 id 的 bean 指定为用户my
@Qualifier注释。
@Autowired
@Qualifier("my")
public void setMy2(My my) {
this.my = my;
}