请直接看原文:
--------------------------------------------------------------------------------------------------------------------------------
一.@Autowired详解
要搞明白@Autowired注解就是要了解它是什么?有什么作用?怎么用?为什么?
- 首先了解一下IOC操作Bean管理,bean管理是指(1)spring创建对象 (2)spring注入属性。当我们在将一个类上标注@Service或者@Controller或@Component或@Repository注解之后,spring的组件扫描就会自动发现它,并且会将其初始化为spring应用上下文中的bean。 而且初始化是根据无参构造函数。先看代码来体会一下这个注解的作用,测试代码如下:(@Data注解是由Lombok库提供的,会生成getter、setter以及equals()、hashCode()、toString()等方法)
@Data
@Service
public class AutoWiredBean {
private int id;
private String name;
public AutoWiredBean(){
System.out.println("无参构造函数");
}
public AutoWiredBean(int id, String name) {
this.id = id;
this.name = name;
System.out.println("有参构造函数");
}
}
在springboot项目的测试类中进行测试,代码如下
@SpringBootTest
@RunWith(SpringRunner.class)
class Springboot02WebApplicationTests {
private AutoWiredBean autoWiredBean;
@Autowired
public Springboot02WebApplicationTests (AutoWiredBean autoWiredBean){
this.autoWiredBean = autoWiredBean;
}
@Test
void contextLoads() {
System.out.println(autoWiredBean);
System.out.println(autoWiredBean.getId()); //0
System.out.println(autoWiredBean.getName()); //null
}
}
控制台输出的结果如下:
将下面代码注释了在运行
/* @Autowired
public Springboot02WebApplicationTests (AutoWiredBean autoWiredBean){
this.autoWiredBean = autoWiredBean;
}*/
输出结果如下:
从这我们可以看到
1.无论有没有使用AutoWiredBean 类,它都被spring通过无参构造函数初始化了。当将被使用时才会创建。就对应了Spring在启动时,默认会立即调用单实例bean的空参构造方法创建bean的对象,并加载到Spring容器中。
2.不用@Autowired的private AutoWiredBean autoWiredBean值为null; 用了@Autowired的private AutoWiredBean autoWiredBean值为真实存在的AutoWiredBean类的对象;
二.有什么用
给对象类型的属性赋值(就是将本来为null的private AutoWiredBean autoWiredBean值赋值为真实存在的AutoWiredBean类的对象),可以用在成员变量、成员方法、构造方法上.
@Autowired 注解注入时首先根据byType注入,当接口存在多个实现类且使用@Service注解的默认bean名字时,根据byName注入。
@Service注解默认bean名字是小写开头的非限定(non-qualified)类名.
如果出现多个实现类可以通过 @Service("userServiceA") 来指定bean名,此时使用@Autowired需要配合@Qualifier("userServiceA")使用.
三.注意:
@Autowired 注解不能用在静态变量和静态方法上, 是因为静态变量和静态方法属于类加载期间,
而@Autowired属于spring上下文容器期间, spring上下文容器期间只是创建类的对象,并不能对属于类的静态变量和静态方法进行操作, 因此,@Autowired加在静态变量和静态方法是无效的,并不能完成赋值功能.