在项目开发阶段,开发环境和实际生产环境是不一样,比如使用的数据库/服务连接配置等。因此,配置多个开发环境profile还是必要的
多环境的配置(yml)方式
配置其实很简单,在resource目录下,新建多个application-${profile}.yml
文件,每个文件代表一种环境。
我们部署dev
和profile
双开发环境,就需要新建application-dev.yml
和application-prod.yml
以及application.yml
。
最后,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金");
}
测试结果