多数项目都会有开发环境、测试环境、生产环境,各个环境配置可能都会不同,因而在构建时,会涉及到环境配置的切换。来回手工修改配置,效率低下,容易出错。能够配置多个含有不一样环境配置的Profile,在构建时指定构建环境,达到多环境下快速灵活构建的目的。mysql
jdbc_driver_class=${jdbc.driver.class} jdbc_connection_url=${jdbc.connection.url} jdbc_username=${jdbc.username} jdbc_password=${jdbc.password}
dev.properties:sql
jdbc.driver.class=com.mysql.jdbc.Driver jdbc.connection.url=jdbc:mysql://localhost:3306/mydb jdbc.username=dev_user jdbc.password=123456
test.properties:apache
jdbc.driver.class=com.mysql.jdbc.Driver jdbc.connection.url=jdbc:mysql://192.168.1.25:3306/mydb jdbc.username=test_user jdbc.password=123456
prod.properties:maven
jdbc.driver.class=com.mysql.jdbc.Driver jdbc.connection.url=jdbc:mysql://www.nocoffee.com:3306/mydb jdbc.username=prod_user jdbc.password=123456
<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.coffee</groupId> <artifactId>coffee-xw</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <profiles> <profile> <id>dev</id> <properties> <!-- 自定义属性env,在不一样环境有不一样的值 --> <env>dev</env> </properties> <activation> <!-- 默认激活dev环境的配置 --> <activeByDefault>true</activeByDefault> </activation> </profile> <profile> <id>test</id> <properties> <env>test</env> </properties> </profile> <profile> <id>prod</id> <properties> <env>prod</env> </properties> </profile> </profiles> <build> <!-- 指定filter,根据最终profile下的env属性获取对应的配置文件 --> <filters> <filter>src/main/prop/${env}.properties</filter> </filters> <!-- 开启资源过滤,让Maven能解析资源文件中的Maven属性 --> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> </build> </project>
构建时,指定参数-P加上profile的id来激活对应的profile。也能够经过
如上,显示的激活dev环境的profile,执行
mvn clean install 时,编译后的config.properties内容为:
jdbc_driver_class=com.mysql.jdbc.Driver jdbc_connection_url=jdbc:mysql://localhost:3306/mydb jdbc_username=dev_user jdbc_password=123456
执行 mvn clean install -Pprod 时,编译后的config.properties内容为:ui
jdbc_driver_class=com.mysql.jdbc.Driver jdbc_connection_url=jdbc:mysql://www.nocoffee.com:3306/mydb jdbc_username=prod_user jdbc_password=123456