关于java:为什么不直接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();
 }

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理