SpringBoot之@Autowired


  • 该注解是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。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM