- 该注解是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。
Spring-Boot之@Autowired
原文:https://www.cnblogs.com/jian-chen/p/14479064.html