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();}