-
父工程pom.xml 中profile配置
<!-- maven 多环境配置 --> <profiles> <profile> <id>dev</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>pre</id> <properties> <profiles.active>pre</profiles.active> </properties> </profile> <profile> <id>prod</id> <properties> <profiles.active>prod</profiles.active> </properties> </profile> </profiles> <build> <resources> <resource> <directory>src/main/resources</directory> <!--是否执行过滤,替换资源文件中的属性--> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> </configuration> </plugin> </plugins> </build>
-
在maven的pom文件中进行多环境变量配置,引用了maven-resource-plugin,在application.properties文件通过以下配置指定不同环境下的配置文件.
spring.profiles.active = ${profiles.active}
-
在集成spring-boot-start-parent的项目中,spring boot将maven-resource-plugins 默认的${name}方式改成了@name@,原有${name}无法再继续使用
1.application.properties 文件(
正常解析
)spring.profile.active = @profiles.active@
install 后,配置文件:
spring.profile.active = dev
2.application.yml 文件(
不推荐使用
)yml类型文件使用@@标识会提示下面问题
found character @ '@' that cannot start any token. (Do not use @ for indentation)
此类问题,如果引入的是普通的配置信息,可以通过增加单引号或者双引号的形式
spring: profile: active: '@profiles.active@'
注意:这种形式编译后相当于字符串解析
编译后文件:
spring: profile: active: 'dev'
-
【推荐】
使用原有${name}方式,在pom文件中增加如下配置,这样properties、yml都适用<build> <pluginManagement> <plugins> <plugin> <artifactId>maven-resources-plugin</artifactId> <configuration> <encoding>utf-8</encoding> <useDefaultDelimiters>true</useDefaultDelimiters> </configuration> </plugin> </plugins> </pluginManagement> </build>
建议使用resource中 exclude、include 实现加载指定环境资源文件。
- 工程目录
- pom.xml
<build> <resources> <!-- 此处使用exclude目的是为了保留application.properties --> <resource> <directory>src/main/resources/</directory> <excludes> <!-- 根据规则排除掉相关文件,此处application.properties不符合排除规则保留改文件 --> <exclude>*-*.*</exclude> </excludes> <!-- 过滤,替换文件内引入的变量 --> <filtering>true</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <!-- 引入指定环境的配置文件 --> <include>*-${profiles.active}.*</include> </includes> <!-- 过滤,替换文件内引入的变量 --> <filtering>true</filtering> </resource> </resources> </build>
使用resource会重新加载资源,所以此处需要开启过滤替换。
- 编译后jar目录
// application.properties // 源文件 spring.profiles.active= ${profiles.active} file-name = application.properties // 编译后 spring.profiles.active= test file-name = application.properties // application-test.properties // 源文件 profiles.active= ${profiles.active} file-name = application-test.properties // 编译后 profiles.active= test file-name = application-test.properties // 程序获取file-name System.out.println(environment.getProperty("file-name")) // 输出内容 application-test.properties