一个项目,在家的时候可能会在本机上运行,在公司可能在内网测试环境运行,上线后会在生产环境运行,在不同的环境中会有一些配置是不一样的,至少数据库就不一样。如果每换一个环境就去改所有配置太过于麻烦,以下方法就是通过一个参数灵活的切换不同的环境
项目结构
pom.xml
- <profiles>
- <profile>
- <id>dev</id>
- <properties>
- <env>dev</env>
- </properties>
- <activation>
- <activeByDefault>true</activeByDefault>
- </activation>
- </profile>
- <profile>
- <id>test</id>
- <properties>
- <env>test</env>
- </properties>
- <activation>
- <activeByDefault>false</activeByDefault>
- </activation>
- </profile>
- </profiles>
- <build>
- <filters>
- <filter>filters/${env}.properties</filter>
- </filters>
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>true</filtering>
- </resource>
- </resources>
- </build>
<profiles>:就是properties文件,通过加载不同的profile来区别不同的环境
<activeByDefault>:true代表当前激活的配置,false代表未激活,如果要切换环境只需要修改true和false,执行maven-update
<filter>:通过激活的profile中的<env>内容来加载filters目录下的不同的properties,自动过滤不同的环境
<filtering>:true就是用filters/${env}.properties的参数值来过滤src/main/resources中的properties文件,之后详解
Test.java
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.Properties;
- import org.springframework.stereotype.Component;
- public class Test {
- static {
- Properties prop = new Properties();
- InputStreamReader in = null;
- try {
- in = new InputStreamReader(Test.class.getClassLoader().getResourceAsStream("aaa.properties"), "UTF-8");
- prop.load(in);
- System.out.println(prop.getProperty("aaa"));
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- in.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
这是一个最基本的静态块,在项目启动的时候,读取aaa.properties文件中的参数aaa的值。需要配置spring自动扫描注解
properties
aaa.properties
aaa=${aaa}
这个aaa没有配一个固定参数值,而是用的${aaa},表示根据当前环境的不同过滤不同的值dev.properties
aaa=bbb
dev就是当前激活的开发环境,这里的aaa就是要过滤替代${aaa}的值。在测试环境test.properties中可以设置不同的值运行项目
如图,实际加载的aaa参数的值是dev.properties而不是aaa.properties