SpringBoot配置两个一样的Bean,区分两个配置类——@Primary
1.SpringBoot的基础2.SpringBoot的@Resource和@Autowired+@Qualifier使用
3.SpringBoot配置两个一样的Bean,区分两个配置类——@Primary
4.SpringBoot项目预加载数据——ApplicationRunner、CommandLineRunner、InitializingBean 、@PostConstruct区别5.SpringBoot获取配置:@Value、@ConfigurationProperties方式6.SpringBoot注入时设置《多例》7.在线程中使用Spring的Bean的方法、不推荐把“线程”注入到Spring8.SpringBoot读取Resources下的文件
1、@Primary
作用:
- 指定默认bean。
- 当没有根据名字显示要注入哪个bean的时候,默认使用打了@Primary标签的bean
2、配置两个一样的bean
@Configuration public class MyThymeLeafConfig { @Resource private ApplicationContext applicationContext; /** 自定义的bean(默认) * @return SpringTemplateEngine * @Primary :<li>作用:指定使用名为“myTemplateEngine”的bean作为默认bean。</li> * <li>这样,当您在需要使用SpringTemplateEngine的地方没有指定@Qualifier注释时,Spring将使用该默认bean。</li> * <li>使用@Resource时,可直接设置名字。不用使用@Qualifier注释</li> */ @Bean(name = "myTemplateEngine") @Primary public SpringTemplateEngine myTemplateEngine(){ SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setEnableSpringELCompiler(true); return templateEngine; } //---------------------------------------------- /** 自定义的bean2 * @return SpringTemplateEngine */ @Bean(name = "myTemplateEngine2") public SpringTemplateEngine myTemplateEngine2(){ SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setEnableSpringELCompiler(true); return templateEngine; } }
3、使用
- 可以使用 @Resource 也可以使用 @Autowired + @Qualifier
- 推荐使用 @Resource
- @Resource和@Autowired + @Qualifier区别见:https://www.cnblogs.com/kakarotto-chen/p/17408564.html
- 建议注入的时候都加上bean的名字,这样速度快
@Resource(name = "myTemplateEngine") private SpringTemplateEngine springTemplateEngine1Html; @Resource(name = "myTemplateEngine2") private SpringTemplateEngine springTemplateEngine2Xml;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)