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