Maven多環境配置


多數項目都會有開發環境、測試環境、生產環境,各個環境配置可能都會不一樣,於是在構建時,會涉及到環境配置的切換。來回手工修改配置,效率低下,容易出錯。可以配置多個含有不同環境配置的Profile,在構建時指定構建環境,達到多環境下快速靈活構建的目的。

項目結構:

config.properties:

jdbc_driver_class=${jdbc.driver.class}
jdbc_connection_url=${jdbc.connection.url}
jdbc_username=${jdbc.username}
jdbc_password=${jdbc.password}

prop下的dev.properties、test.properties、prod.properties分別對應開發、測試、生產環境的配置。

dev.properties:

jdbc.driver.class=com.mysql.jdbc.Driver
jdbc.connection.url=jdbc:mysql://localhost:3306/mydb
jdbc.username=dev_user
jdbc.password=123456

test.properties:

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:

jdbc.driver.class=com.mysql.jdbc.Driver
jdbc.connection.url=jdbc:mysql://www.nocoffee.com:3306/mydb
jdbc.username=prod_user
jdbc.password=123456

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.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。也可以通過 指定默認激活的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內容為:

jdbc_driver_class=com.mysql.jdbc.Driver
jdbc_connection_url=jdbc:mysql://www.nocoffee.com:3306/mydb
jdbc_username=prod_user
jdbc_password=123456


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM