配置文件的多环境切换
- 1.在pom文件中定义profiles
<profiles>
<profile>
<id>develop</id>
<properties>
<profiles.active>dev</profiles.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<profiles.active>test</profiles.active>
</properties>
</profile>
<profile>
<id>product</id>
<properties>
<profiles.active>product</profiles.active>
</properties>
</profile>
</profiles>
-
2.在resource下新建application-${profiles.active}.properties文件
- 在pom的build中指定resource
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>application-dev.properties</exclude>
<exclude>application-test.properties</exclude>
<exclude>application-product.properties</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>application-${profiles.active}.properties</include>
<include>application.properties</include>
</includes>
</resource>
</resources>
- 在application.properties文件中添加配置
spring.profiles.active=@profiles.active@
- 在application.properties文件中添加配置
Bean的切换
- 注解
@Profile
@Profile("dev")
代码业务的切换
@Autowired
private Environment environment;
String[] activeProfiles = environment.getActiveProfiles();
environment.getProperty("key");