创建一个maven的springboot项目:
pom.xml如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.pp.test</groupId> <artifactId>properties-test</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>properties-test</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> <filters> <filter>src/main/profiles/profile-${profiles.active}.properties</filter> </filters> <resources> <resource> <filtering>true</filtering> <directory>src/main/resources</directory> </resource> </resources> </build> <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>prod</id> <properties> <profiles.active>prod</profiles.active> </properties> </profile> </profiles> </project>
application.properties如下:
jdbc.driverClassName=${jdbc.driverClassName} jdbc.url=${jdbc.url} jdbc.username=${jdbc.username} jdbc.password=${jdbc.password}
profile-dev.properties 文件内容:
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql:///db_users jdbc.username=root jdbc.password=root
使用mvn package -Pdev 打包后,application.propertes文件中内容没有被替换。
filtering无效的原因是,pom.xml继承了spring boot的依赖
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> </parent>
点开这个依赖的pom.xml,我们发现
spring boot把默认的占位符号${}改成了@
找到原因了,那怎么解决就很简单了。
方法一:
在pom.xml里面添加如下内容
<properties> <resource.delimiter>${}</resource.delimiter> </properties>
方法二:
application.properties里面不用${},改成@
[email protected]@ [email protected]@ [email protected]@ [email protected]@方法三:
pom.xml不继承spring-boot-starter-parent,dependency里面配置全部的依赖和版本号(继承了之后,很多依赖不用写version)
方法四:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> </parent>
改成:
<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>1.5.9.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>