当前位置 博文首页 > blackball1998的博客:多环境配置
需要配置多个环境下的配置文件,只需要以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