在用maven分环境打包springboot项目时,遇到在.yml或者.properties读取pom.xml变量时,无法解析问题。
以下代码是我在application.properties里面用@@读取pom.xml里的分环境打包设置的变量profileActive。
spring.application.name=ceshi
server.servlet.context-path=/ceshi
spring.profiles.active=@profileActive@
以下代码是我在pom.xml里面设置的分环境打包的信息,以及资源文件设置的信息.
<build>
<!-- 这样也可以把所有的xml文件,打包到相应位置。 -->
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.tld</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.tld</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.test.testApplication</mainClass>
<outputDirectory>target</outputDirectory>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>dev</id>
<properties>
<profileActive>dev</profileActive>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>devjm</id>
<properties>
<profileActive>devjm</profileActive>
</properties>
</profile>
<!--正式环境-->
<profile>
<id>pro</id>
<properties>
<profileActive>pro</profileActive>
</properties>
</profile>
</profiles>
在设置里以上信息后发现,在用maven选择了dev环境打包后,生成的jar文件里application.properties中的内容还是
spring.application.name=ceshi
server.servlet.context-path=/ceshi
spring.profiles.active=@profileActive@
@profileActive@没有解析,@profileActive@应该替换为dev。
解决办法:
在build->resources->resource->里添加filtering标签并设置为true,这样就可以解析pom.xml里的变量了。
<build>
<!-- 这样也可以把所有的xml文件,打包到相应位置。 -->
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.tld</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.tld</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.test.testApplication</mainClass>
<outputDirectory>target</outputDirectory>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>dev</id>
<properties>
<profileActive>dev</profileActive>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>devjm</id>
<properties>
<profileActive>devjm</profileActive>
</properties>
</profile>
<!--正式环境-->
<profile>
<id>pro</id>
<properties>
<profileActive>pro</profileActive>
</properties>
</profile>
</profiles>