使用maven管理項目中的依賴,非常的方便。同時利用maven內置的各種插件,在命令行模式下完成打包、部署等操作,可方便后期的持續集成使用。
但是每一個maven工程(比如web項目),開發人員在開發時,會使用一種配置文件,比如數據庫配置,而測試環境可能使用另一種配置文件。
打包完成后,手動調整配置文件,工作重復度很高,因此查找方法,實現“maven根據不同的運行環境,打包不同的配置文件”的目的。
按環境名稱建立配置文件目錄
在src/main/resources目錄下面,按照環境名稱建立配置文件目錄。這里有兩個環境:test、product。
同時發現test、product目錄中的文件和目錄之外的文件基本相同。這是為了方便開發人員本地開發時本地調試,所以沒有建立dev環境的配置文件目錄。
pom.xml中增加插件
主要關注標紅的插件maven-resources-plugin,以及標紅的配置部分。
注意:目前經過測試,發現resources目錄文件拷貝會在validation階段之后compile階段之前執行,為了保證指定環境的配置文件在resources目錄拷貝之后執行,使用compile階段;overwrite設置為true,強制覆蓋原有文件。
使用maven-resources-plugin插件,在compile階段實現指定目錄中配置文件的拷貝操作。
<build> <finalName>Lantech</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> <encoding>UTF-8</encoding> </configuration> </plugin> <!-- 不同環境的配置文件選擇 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.6</version> <executions> <execution> <id>copy-resources</id> <phase>compile</phase> <goals> <goal>copy-resources</goal> </goals> <configuration>
<!-- 覆蓋原有文件 -->
<overwrite>true</overwrite> <outputDirectory>${project.build.outputDirectory}</outputDirectory> <!-- 也可以用下面這樣的方式(指定相對url的方式指定outputDirectory) <outputDirectory>target/classes</outputDirectory> --> <!-- 待處理的資源定義 --> <resources> <resource> <!-- 指定resources插件處理哪個目錄下的資源文件 --> <directory>src/main/resources/${package.environment}</directory> <filtering>false</filtering> </resource> </resources> </configuration> <inherited></inherited> </execution> </executions> </plugin> </plugins> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
pom.xml中增加profiles配置
使用profiles可為maven命令執行時,激活不同的變量,並依據此變量同上述的插件配合,完成指定目錄中配置文件拷貝操作。
<profiles> <profile> <id>dev</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <package.environment>dev</package.environment> </properties> </profile> <profile> <id>test</id> <properties> <package.environment>test</package.environment> </properties> </profile> <profile> <id>product</id> <properties> <package.environment>product</package.environment> </properties> </profile> </profiles>
執行打包命令
mvn clean package
mvn clean package -Pdev
mvn clean package -Ptest
mvn clean package -Pproduct
執行命令,指定-P參數,啟用指定的profile。
默認的dev目錄是不存在的,因此原有的配置文件不會被覆蓋。當啟動其他profile時,會覆蓋原有的文件,實現不同環境不同配置文件的打包需求。