@Autowired 注解可以加在构造器、方法、参数、属性、注解类型上。如果有参构造器或 @Bean 注解方法只有一个入参,则可以省略 @Autowired 不写。
1、属性
@Autowired
MyService bbb;
2、构造器
@Autowired
public MyAuto(MyService bbb) {
this.bbb = bbb;
}
// 或者去掉 @Autowired 也可以
public MyAuto(MyService bbb) {
this.bbb = bbb;
}
3、方法
@Autowired
public void setBbb(MyService bbb) {
this.bbb = bbb;
}
@Autowired 自动查找 Bean 的顺序
- 根据 @Qualifier 指定的 Bean 名字查找
- 如果没有指定 @Qualifier,则根据 @Primary 注解查找
- 如果没有指定 @Primary,则把属性名当作 Bean 名字查找
- 如果还没找到,则根据类型查找,如果有多个相同类型的类,则无法找到,报错
指定 @Qualifier
@Autowired
@Qualifier("bbb")
MyService xx;
指定 @Primary
public interface MyService {}
@Service
@Primary
class Aaa implements MyService {}
@Service
class Bbb implements MyService {}
@Service
class Ccc implements MyService {}
注入方式如何选择
Spring 官方建议使用构造器方法注入,引用原话:
The Spring team generally advocates constructor injection, as it lets you implement application components as immutable objects and ensures that required dependencies are not null. Furthermore, constructor-injected components are always returned to the client (calling) code in a fully initialized state. As a side note, a large number of constructor arguments is a bad code smell, implying that the class likely has too many responsibilities and should be refactored to better address proper separation of concerns.
大概翻译过来的意思是:
使用构造器注入,可以声明变量为 final,并能确保依赖的对象不是 null,此外,构造器注入能保证对象初始化完成。而如果构造器参数有很多,那可能这个代码需要重构了。