使用Autowired注解进行属性自动注入时,常常会有两个类同时继承一个接口的情况:
public interface InterfaceService {
void doSomething();
}
@Service("interfaceServiceA")
public class InterfaceServiceA implements InterfaceService{
public void doSomething(){
System.out.println("xxx");
}
}
@Service("interfaceServiceB")
public class InterfaceServiceB implements InterfaceService{
public void doSomething(){
System.out.println("xxx");
}
}
@Controller
public class MvcController{
@Autowired
InterfaceService interfaceServiceB;
}
当存在上面的情况时,一直以为Autowired只通过byType进行Bean的自动装配。需要加@Qualifier("interfaceServiceB")才能注入具体的Bean。
其实Autowired自动装配类似于首先进行byType,当发现有多个时再进行byName。
所以,当接口与实现类一对一时,属性名称可以任意定义。一对多时,需要注意属性名必须与Bean在Spring 容器中的ID一致才能有效。
本文详细探讨了在Spring框架中使用@Autowired注解进行依赖注入的原理。特别关注了一对多情况下,如何通过属性名匹配来指定具体注入哪个Bean。解释了@Autowired不仅按类型装配,还会在类型不唯一时尝试按名字匹配。

被折叠的 条评论
为什么被折叠?



