多环境配置
在实际开发中,我们往往需要区分不同环境下所运行的代码,例如在开发过程中使用开发环境,在测试过程中使用测试环境,在线上发布时候使用正式环境
使用Spring Boot的配置文件,可以方便地区分不同的配置环境,在需要的时候激活相应的环境,从而区分不同环境下的代码行为
使用多配置文件
需要配置多个环境下的配置文件,只需要以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