使用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一致才能有效。