>

Spring注解之@Profile和@ActiveProfiles

@Profile 注解:
1.使用@Profile的原因
在平时的开发中,通常开发一个开发库,测试一个测试库,生产一个生产库。
我们将数据库信息写在一个配置文件中,在部署的时候我们将配置文件改成对应的配置文件,这样改来改去非常麻烦。
在使用@Profile后,我们就可以定义3个配置文件dev、sit、pro其分别对应3个profile,在实际运行的时候只需给定一个参数,容器就会加载激活的配置文件,这样就简便了。
2.使用实战
(1)测试bean

复制代码
public class TestBean {
    private String content;

    public TestBean(String content) {
        super();
        this.content = content;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
    
}
复制代码

(2)测试配置

复制代码
@Configuration
public class TestConfig {
    @Bean
    @Profile("dev")
    public TestBean devTestBean() {
        return new TestBean("from development profile");
    }
    
    @Bean
    @Profile("pro")
    public TestBean proTestBean() {
        return new TestBean("from production profile");
    }
}
复制代码

(3)测试

复制代码
@RunWith(SpringJUnit4ClassRunner.class) 
//在SpringJUnit4ClassRunner在JUnit环境下提供Spring  TestContext Framework功能
@ContextConfiguration(classes={TestConfig.class}) //加载配置ApplicationContext,classes属性用来加载类
@ActiveProfiles("pro")//声明活动的profile
public class DemoBeanIntegrationTests {
    @Autowired
    private TestBean testBean;
    
    @Test
    public void prodBeanShouldInject() {
        String expected="from production profile";
        String actual=testBean.getContent();
        Assert.assertEquals(expected, actual);
    }
    
}
复制代码

3.测试结果

(1)@ActiveProfiles(“pro”)测试

(2)@ActiveProfiles(“dev”)测试

 

 

参考文章:

https://blog.csdn.net/weixin_43671840/article/details/87972393

posted @   字节悦动  阅读(1642)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示