SpringBoot的@Resource和@Autowired+@Qualifier使用

 


1、区别

参考:

https://blog.csdn.net/xhbzl/article/details/126765893

https://blog.csdn.net/qq_40263124/article/details/124238530

2、使用

2.1、注入配置类

  • 比如注入config的bean
@Configuration
public class MyThymeLeafConfig {
@Resource
private ApplicationContext applicationContext;
/** 自定义的bean
*/
@Bean(name = "myTemplateEngine")
public SpringTemplateEngine myTemplateEngine(){
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
SpringResourceTemplateResolver templateResolver = myTemplateResolver();
templateEngine.setTemplateResolver(templateResolver);
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
  • 使用:@Autowired
@Autowired
@Qualifier("myTemplateEngine")
private SpringTemplateEngine springTemplateEngine2Xml;
  • 使用:@Resource
@Resource(name = "myTemplateEngine")
private SpringTemplateEngine springTemplateEngine1Html;

上面两种使用方法是等价的。

2.2、注入业务类、实现类

  • 略……
  • 当只有一个Impl实类的时候,随便用哪个都差不多,>=2的时候,最好用@Resource,比@Autowired + @Qualifier()效率高

3、推荐使用@Resource

  • @Autowired
效率低下,先按类型查找,再按名字查找
  • @Resource
会先按byName去找,如果没找到则会byType去找。如果设置了name属性,则只会按byName去找,找不到就报错。速度快
按名字查找,后面要跟参数name,好处:当有多个Impl实现类时,可以通name快速找到
  • 总结
当只有一个Impl实类的时候,随便用哪个都差不多,>=2的时候,最好用@Resource,比@Autowired + @Qualifier()效率高

posted on   C_C_菜园  阅读(346)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示