• 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类:

    @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

    代码地址

    参考

  • 相关阅读:
    学习笔记之C++ How to Program(part)
    Makefile相关资料
    [ZZ]指针Guide
    [ZZ]make命令与makefile文件的写法
    SQLite数据库简介及资源下载
    程序员天生码农命?
    Application标签中有三个事件运行顺序
    Flex 项目案例集锦
    flex简介
    Flex连接数据库三种方法
  • 原文地址:https://www.cnblogs.com/Franken-Fran/p/multi_profiles.html
Copyright © 2020-2023  润新知