SpringBoot的@Resource和@Autowired+@Qualifier使用
1.SpringBoot的基础
2.SpringBoot的@Resource和@Autowired+@Qualifier使用
3.SpringBoot配置两个一样的Bean,区分两个配置类——@Primary4.SpringBoot项目预加载数据——ApplicationRunner、CommandLineRunner、InitializingBean 、@PostConstruct区别5.SpringBoot获取配置:@Value、@ConfigurationProperties方式6.SpringBoot注入时设置《多例》7.在线程中使用Spring的Bean的方法、不推荐把“线程”注入到Spring8.SpringBoot读取Resources下的文件
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()效率高
合集:
SpringBoot基础
分类:
SpringBoot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)