当前位置 博文首页 > blackball1998的博客:多环境配置

    blackball1998的博客:多环境配置

    作者:[db:作者] 时间:2021-06-09 09:16

    多环境配置

    使用多配置文件

    需要配置多个环境下的配置文件,只需要以application-{profiles}.yml的格式命名配置文件,{profiles}的值既配置文件的环境名称

    在这里插入图片描述

    我们创建一个组件,从配置文件中取值,用来测试环境切换

    @Data
    @Component
    @ConfigurationProperties(prefix = "person")
    public class Person {
        private String name;
        private int age;
    }
    

    application.yml文件中的配置如下

    person:
      name: 张三
      age: 18
    

    application-dev.yml文件中的配置如下

    person:
      name: 李四
      age: 20
    

    如果不指定激活环境,会使用默认的application.yml文件中的配置

    @SpringBootTest
    class DemoApplicationTests {
        @Autowired
        Person person;
    
        @Test
        void contextLoads() {
            System.out.println(person);
        }
    
    }
    

    在这里插入图片描述

    指定激活的环境,只需要在主配置文件application.yml中使用spring.profiles.active

    person:
      name: 张三
      age: 18
    spring:
      profiles:
        active: dev
    

    在这里插入图片描述

    测试发现加载了dev环境中的配置

    或者也可以在项目打包成jar包后,用命令行参数--spring.profiles.active来指定激活的环境

    azure-mac:test Azure$ java -jar demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev
    

    激活多个配置环境

    假设我现在需要激活多个配置环境,比如我在dev环境中配置了组件的name属性

    person:
      name: 李四
    

    在test环境中配置了组件的age属性

    person:
      age: 22
    

    要激活多个配置环境,只需要在主配置文件application.yml中使用spring.profiles.include

    spring:
      profiles:
        include:
          - dev
          - test
    

    这样dev环境和test环境下的配置就会同时激活

    在这里插入图片描述

    使用文档块

    我们也可以使用单个配置文件,用划分文档块的方式区分多个环境

    划分文档块,只需要使用三个横杠---,横杠上下的内容相当于不同文件中的内容,然后使用spring.config.activate.on-profile在不同的文档块中指定文档块的环境

    spring:
      profiles:
        active: dev
    person:
      name: 张三
      age: 18
    ---
    spring:
      config:
        activate:
          on-profile: dev
    person:
      name: 李四
      age: 20
    ---
    spring:
      config:
        activate:
          on-profile: test
    person:
      name: 王五
      age: 22
    
    下一篇:没有了