在學習寫Service層的實現類時,發現直接在變量上註解 @Autowired 有個警告提示Field injection is not recommended 。
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findAllById(int id) {
return userMapper.findAllById(id);
}
}
Field injection is not recommended
Inspection info: Spring Team recommends: "Always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies".
意思是說“變量依賴注入是不被建議的方式”。它建議“總是採用構造器注入的方式建立依賴注入”。
關於依賴注入一般有三種方式
#1#-> 變量注入(Field Injection)
@Autowired
private UserMapper userMapper;
#2#-> 構造器注入(Constructor Injection)
private UserMapper userMapper;
@Autowired
public UserServiceImpl(UserMapper userMapper) {
this.userMapper = userMapper;
}
#3#-> setter方法注入 (Setter Injection)
private UserMapper userMapper;
@Autowired
public void setUserMapper(UserMapper userMapper){
this.userMapper = userMapper;
}
關於三種方式的優缺點,因爲剛開始學習暫時沒啥感覺,網上有很多資料分析得足夠透徹了,先放在這裏,以後有新的感悟再更新。
@Autowired的三種使用方式 https://www.cnblogs.com/wang-yaz/p/9340156.html
使用@Autowired註解警告Field injection is not recommended https://blog.csdn.net/zhangjingao/article/details/81094529
spring爲何推薦使用構造器注入 https://www.jianshu.com/p/4694b1a82546
@Autowired的使用:推薦對構造函數進行註釋 https://blog.csdn.net/hegongxu/article/details/78114437
結論
Spring3.0官方文檔建議使用setter注入覆蓋構造器注入。
Spring4.0官方文檔建議使用構造器注入。
1-> 如果注入的屬性是必選的屬性,則通過構造器注入。
2-> 如果注入的屬性是可選的屬性,則通過setter方法注入。
3-> 至於field注入,不建議使用。