主题
Profile
Profile 本质上代表一种用于组织配置信息的维度,在不同场景下可以代表不同的含义。
1、如果 Profile 代表的是一种状态,可以使用open、halfopen、close等值来分别代表全开、半开和关闭等。
2、如果系统需要设置一系列的模板,每个模板中保存着一系列配置项,那么也可以针对这些模板分别创建 Profile。
application-dev.yml
application-test.yml
为了达到集中化管理的目的,Spring Boot 对配置文件的命名也做了一定的约定
1、label 表示配置版本控制信息
2、profile 则用来指定该配置文件所对应的环境。
在 Spring Boot 中,配置文件同时支持.properties 和 .yml 两种文件格式
/{application}.yml
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
Yaml特别适合用来表达或编辑数据结构和各种配置文件。
激活1个Profile
yaml
spring:
profiles:
active: test
激活多个Profile
方法1
yaml
spring:
profiles:
active: prod, myprofile1, myprofile2
较推荐
方法2
yaml
spring:
profiles: test #test 环境相关配置信息
---
spring:
profiles: prod #prod 环境相关配置信息
命令行指定环境
shell
java –jar wxserver-0.0.1.jar --spring.profiles.active=prod
代码控制与Profile
@Profile 注解来指定具体所需要执行的 DataSource 创建代码,可以达到与使用配置文件相同的效果。
java
@Configuration
public class DataSourceConfig {
@Bean
@Profile("dev")
public DataSource devDataSource() {
//创建 dev 环境下的 DataSource
}
@Bean()
@Profile("prod")
public DataSource prodDataSource(){
//创建 prod 环境下的 DataSource
}
}
比如可以基于CommandLineRunner接口在开发环境下,初始化运行环境的数据,
java
@Profile("dev")
@Configuration
public class DevDataInitConfig {
@Bean
public CommandLineRunner dataInit() {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
//执行 Dev 环境的数据初始化
};
}