maven多環境配置及檔案命名
阿新 • • 發佈:2018-12-16
網上有很多相關的配置的部落格,都比較零散。找到了可以用的方案,測試有效,做記錄備份~
專案中很多配置項,全部彙總到resources/properties目錄下,但是測試環境和生產環境的專案需要的配置檔案是不一樣的,每次打包部署不可能還修改配置檔案,因此想到偷懶。
包含兩個效果:
1、根據打包站點,將對應的配置檔案,放到輸出目錄
2、根據打包站點,指定輸出檔名
一、多環境打包指定配置檔案
目錄結構
pom.xml檔案關鍵配置大概就是這樣,可以作為參考:
<?xml version="1.0" encoding="UTF-8"?>
<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.vzoom</groupId>
<artifactId >test_demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>test_demo</name>
<url>http://www.example.com</url>
<!-- 環境節點配置 -->
<profiles>
<!-- 本地環境 -->
<profile >
<id>local</id>
<properties>
<package.environment>local</package.environment>
</properties>
<!-- 是否預設 -->
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<!-- 開發環境 -->
<profile>
<id>dev</id>
<properties>
<package.environment>dev</package.environment>
</properties>
</profile>
<profile>
<!-- 測試環境 -->
<id>test</id>
<properties>
<package.environment>test</package.environment>
</properties>
</profile>
<profile>
<!-- 生產環境 -->
<id>prod</id>
<properties>
<package.environment>prod</package.environment>
</properties>
</profile>
</profiles>
<build>
<!--
指定打包後的檔名,不指定預設是 artifactId 的值
${package.environment} 環境節點名
${project.name} 專案名
${version} 版本號
*根據環境指定專案打包目錄時,本地只會存最新的一份,不會出現檔案重複的問題
-->
<finalName>${project.name}-${package.environment}-${version}</finalName>
<!-- 過濾原有的resources/properties目錄下的配置檔案 -->
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>**/properties/**</exclude>
</excludes>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<webResources>
<!-- 根據環境節點將配置檔案編譯到對應的目錄上 -->
<resource>
<directory>src/main/resources/properties/${package.environment}</directory>
<targetPath>WEB-INF/classes/properties</targetPath>
<filtering>true</filtering>
</resource>
</webResources>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
二、打包命令
打包test環境:mvn clean install -P test
以上,作為日後備用