- 該注解是Spring依賴注入的關鍵,例如上例StudentController中注入StudentService
@Autowired
private StudentService studentService;
private StudentService studentService = new StudentServiceImp();
- 但是,通過new關鍵字創建需要StudentController類依賴於StudentServiceImp類。而Spring通過@Autowired注解把對象的創建交給了Spring容器,StudentController類不再依賴於StudentServiceImp類,實現了解耦,提高了系統的可維護性。
- 只要是業務層接口StudentService不變,修改其實現類StudentServiceImp,甚至換一個實現類,都不影響StudentController。
- @Autowired是根據類型注入Bean的,該處出入的Bean的類型是StudentService。當Spring容器擁有該類型的多個Bean時(例如有多個實現類),以上注入方式有誤,因為不能確定唯一的StudentService類型的Bean,這是需要使用@Qualifier指定Bean的id。