SpringBoot配置两个一样的Bean,区分两个配置类——@Primary

 


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(name = "myTemplateEngine")
private SpringTemplateEngine springTemplateEngine1Html;
@Resource(name = "myTemplateEngine2")
private SpringTemplateEngine springTemplateEngine2Xml;

posted on   C_C_菜园  阅读(1624)  评论(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
点击右上角即可分享
微信分享提示