Spring Boot多环境配置

在项目开发阶段,开发环境和实际生产环境是不一样,比如使用的数据库/服务连接配置等。因此,配置多个开发环境profile还是必要的

多环境的配置(yml)方式

配置其实很简单,在resource目录下,新建多个application-${profile}.yml文件,每个文件代表一种环境。

我们部署devprofile双开发环境,就需要新建application-dev.ymlapplication-prod.yml以及application.yml

img

最后,application.yml里面开启需要的环境配置,这里启动的是prod环境

spring:
  profiles:
    active: prod

单元测试

使用spring el表达式测试是否真的做到环境之间的切换

不同环境使用不同配置变量值

application-dev.yml中添加下面一段:

com:
  luzj:
    name: 开发环境
    weight: 3000金

application-prod.yml添加:

com:
  luzj:
    name: 生产环境
    weight: 5000金

添加实体类,使用El表达式注入application-${profile}.yml的值

添加Person类:

扫描二维码关注公众号,回复: 3134526 查看本文章
@Component
public class Person {
    @Value("${com.luzj.name}")
    private String name;
    @Value("${com.luzj.weight}")
    private String weight;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getWeight() {
        return weight;
    }

    public void setWeight(String weight) {
        this.weight = weight;
    }
}
  • 我们使用@Value给域注入配置文件中的值

单元测试

    //spring.profiles.active = dev
    @Test
    public void testDev() {
        Assert.assertEquals(person.getName(), "开发环境");
        Assert.assertEquals(person.getWeight(), "3000金");
    }

    //spring.profiles.active = prod
    @Test
    public void testProd() {
        Assert.assertEquals(person.getName(), "生产环境");
        Assert.assertEquals(person.getWeight(), "5000金");
    }

测试结果
img
img

代码地址

参考

猜你喜欢

转载自www.cnblogs.com/Franken-Fran/p/multi_profiles.html