首页 > 编程语言 > 详细

Spring-Boot之@Autowired

时间:2021-03-04 12:08:38      阅读:40      评论:0      收藏:0      [点我收藏+]
  • 该注解是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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!