下面是@Autowired的作用域
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
- 构造方法
- 方法
- 参数
- 属性
- 注解类型
本文主要介绍一下,写在构造方法和属性上的区别,举一个例子来说明
@Component
public class C2 {
public void say(){
System.out.println("hello world c2");
}
}
@Component
public class C11 {
@Autowired
C2 c2;
C11(){
c2.say();
}
}
我们在C11这个类的构造方法里调用c2的say方法,运行后发现提示空指针异常
原因就是,Spring Bean的生命周期是先实例化然后再进行属性注入的, 所以,在调用say方法的时候,c2还是没有注入的,可以通过在构造函数上添加@Autowired来解决
改成下面这种
@Component
public class C11 {
@Autowired
C11(C2 c2){
c2.say();
}
C11(){
System.out.println("c11 no param construct");
}
}
这里为什么要加@Autowired呢?如果只有一个构造函数,可以不加,但有多个构造函数的时候就必须指定使用哪个。