为什么不直接@Autowired注入交由spring容器管理的Bean,而是选择构造注入?
文章目录
autowire注入方式,在spring4.0后不推荐,原因是可能会造成循环依赖的问题推荐采用构造器或者setter方法注入,示例:
private final Init init;
@Autowired
public DepositServiceImpl(Init init) {
this.init = init;
}@Autowired和构造方法执行的顺序解析
先看一段代码,下面的代码能运行成功吗?
@Autowired
private User user;
private String school;
public UserAccountServiceImpl(){
this.school = user.getSchool();
}答案是不能。因为Java类会先执行构造方法,然后再给注解了@Autowired 的user注入值,所以在执行构造方法的时候,就会报错。报错信息可能会像下面:
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 throw exception; nested exception is java.lang.NullPointer
java.lang.NullPointerException报错信息说:创建Bean时出错,出错原因是实例化bean失败,因为bean时构造方法出错,在构造方法里抛出了空指针异常。
解决办法是,使用构造器注入,如下:
private User user;
private String school;
@Autowired
public UserAccountServiceImpl(User user){
this.user = user;
this.school = user.getSchool();
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论