博客 / 詳情

返回

為什麼不直接@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();
 }
user avatar lankerens 頭像 biubiubiu_5ea3ee0e6b5fd 頭像 91cyz 頭像 tengteng_5c7902af4b01e 頭像 u_16213560 頭像 chengxuyuanxiaohui 頭像 abai_681266b7f0de8 頭像 huaidiaodeya 頭像
8 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.