Spring @autowired注解

一、在接口实现类中,使用到@Autowired 注解,下面是该注解使用的类java

二、Spring@Autowired注解与自动装配spring

@Autowired顾名思义,就是自动装配,其做用是为了消除代码Java代码里面的getter/setter与bean属性中的property。固然,getter看我的需求,若是私有属性须要对外提供的话,应当予以保留。函数

 

这个注解就是spring能够自动帮你把bean里面引用的对象的setter/getter方法省略,它会自动帮你set/get。this

 

其实在启动spring IoC时,容器自动装载了一个AutowiredAnnotationBeanPostProcessor后置处理器,当容器扫描到@Autowied、@Resource或@Inject时,就会在IoC容器自动查找须要的bean,并装配给该对象的属性指针

 

三、@Autowired 能够对成员变量、方法以及构造函数进行注释。那么对成员变量和构造函数进行注释又有什么区别呢?code

@Autowired和构造方法执行的顺序解析对象

  先看一段代码,下面的代码能运行成功吗?接口

@Autowired
 private User user;
 private String school;

 public UserAccountServiceImpl(){
     this.school = user.getSchool();
 }

  答案是不能。get

  由于Java类会先执行构造方法,而后再给注解了@Autowired 的user注入值,因此在执行构造方法的时候,就会报错。it

  报错信息可能会像下面: 

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name ‘...‘ defined in file [....class]: Instantiation of bean failed; 
nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate 
[...]: Constructor threw exception; nested exception is java.lang.NullPointerException

报错信息说:建立Bean时出错,出错缘由是实例化bean失败,由于bean时构造方法出错,在构造方法里抛出了空指针异常。

  解决办法是,使用构造器注入,以下:

private User user;
 private String school;

 @Autowired
 public UserAccountServiceImpl(User user){
     this.user = user;
     this.school = user.getSchool();
 }

 能够看出,使用构造器注入的方法,能够明确成员变量的加载顺序。

  PS:Java变量的初始化顺序为:静态变量或静态语句块–>实例变量或初始化语句块–>构造方法–>@Autowired

      @Autowired自己就是单例模式,只会在程序启动时执行一次,即便不定义final也不会初始化第二次,因此这个final是没有意义的吧。

相关文章
相关标签/搜索