配置文件列表:
目的:
根据环境动态读取配置,例如开发环境dev,会读取application.yml、application-dev.yml、interface-dev.properties
配置:
方式一:
application.yml
spring:
profiles:
active: @profileActive@
pom.xml
<profiles>
<profile>
<id>dev</id>
<properties>
<profileActive>dev</profileActive>
</properties>
</profile>
<profile>
<id>test</id>
<properties>
<profileActive>test</profileActive>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>prod</id>
<properties>
<profileActive>prod</profileActive>
</properties>
</profile>
<profile>
<id>pre</id>
<properties>
<profileActive>pre</profileActive>
</properties>
</profile>
</profiles>
idea maven插件快速切换环境也可以启动命令参数切换环境
方式二:
application.yml
spring:
profiles:
active: dev,test,pre,prod
不需要配置pom.xml,启动命令参数切换环境
读取配置内容:
1.读取application 前缀的配置文件:
application-dev.yml
dynamicParams:
name: test
方式一:
单个参数读取
@Value("${dynamicParams,name}")
private String name;
方式二:
读取成对象参数
@Configuration
@ConfigurationProperties(prefix = "dynamicParams")
@Data
public class DynamicParams {
private String name;
}
需要的地方注入
@Autowired
private DynamicParams dynamicParams;
2.读取interface 前缀的配置文件:
interface-dev.properties
dynamicParams.name=test
方式一:
单个参数读取
@PropertySource(value = "classpath:interface-${spring.profiles.active}.properties")
public class Test {
@Value("${dynamicParams.name}")
private String name;
}
方式二
读取成对象参数
@PropertySource(value = "classpath: interface-${spring.profiles.active}.properties")
@Configuration
@ConfigurationProperties(prefix = "pojo")
@Data
public class DynamicParams {
private String name;
}
需要的地方注入
@Autowired
private DynamicParams dynamicParams;
另外:@PropertySource如需读取yml配置文件需要另外实现PropertySourceFactory 工厂类