1.首先了解注入对象注解
1.1 @Autowired 注解 & @Resource 注解
1.1.1 Autowired 和 Resource的区别:
/**
* Autowired是spring注解,默认会根据byType的方式自动注入bean,如果需要使用byName的方式需要配合@Qualifier注解使用
* Autowired注解支持三种注入方式,属性注入、构造函数、set注入
* Resource是Java的注解,默认会根据byName的方式自动注入bean,byName无法找到对应的bean会根据byType的方式
* Resource注解支持两种注入方式,属性注入、set注入
*/
1.1.2 @Autowired的三种注入方式
属性注入
// 属性注入,spring5.0之后不建议直接注入,会产生警告“Field injection is not recommended”
//spring 官方文档推荐 构造函数注入和set注入
@Autowired //属性注入
private AutowiredServiceA autowiredService;
构造函数注入
private final AutowiredInterface autowiredServiceA;
// 构造方法注入 注入
// @Autowired spring4.5之后这个注解可以忽略不写
private AutowiredTest(AutowiredInterface autowiredServiceA) {
this.autowiredServiceA = autowiredServiceA;
}
set注入
private AutowiredInterface autowiredServiceA;
@Autowired // set注入需要加上@Autowired注解,否则 null指针
public void setAutowiredServiceA(AutowiredInterface autowiredServiceA) {
this.autowiredServiceA = autowiredServiceA;
}
注: 如果一个接口下有多个实现类,进行注入的时候,需要用@Qualifier注解
比如:
public interface AutowiredInterface {
String getName();
}
@Service
@Qualifier("AutowiredServiceA") // 用@Qualifier指定名称
public class AutowiredServiceA implements AutowiredInterface{
public String getName(){
return "AutowiredServiceA";
}
}
@Service
@Qualifier("AutowiredServiceB") // 用@Qualifier指定名称
public class AutowiredServiceB implements AutowiredInterface{
@Override
public String getName() {
return "AutowiredServiceB";
}
}
// 注入
private AutowiredInterface autowiredServiceA;
@Autowired // set注入需要加上@Autowired注解,否则 null指针
public void setAutowiredServiceA(@Qualifier("AutowiredServiceA") AutowiredInterface autowiredServiceA) {
this.autowiredServiceA = autowiredServiceA;
}
1.1.3 @Resource的两种注入方式
属性注入
// 如果多个实现类,可以根据实现类的类名首字母小写进行注入
@Resource
private AutowiredInterface autowiredServiceA;
set注入
private AutowiredInterface autowiredServiceB;
@Resource
public void setAutowiredServiceB(AutowiredInterface autowiredServiceB) {
this.autowiredServiceB = autowiredServiceB;
}