在學習Spring Boot過程當中,搭建了Melon-Boot這個項目,同時學習到Boot與Maven結合,生成項目的打包方案。咱們也能夠看到不少互聯網公司內部會劃分有開發、測試、發佈等不一樣階段的環境,不一樣的環境之間的服務配置項須要進行區分,切換。常見的環境變量有:數據庫鏈接配置、Zookeeper Dubbox配置、URL資源配置等等。css
本文將給出與Spring Boot類似的配置方法,應用於Spring4.X當中,與Maven相結合,管理不一樣環境的配置文件,經過profile實現不一樣環境的打包。java
在項目pom中定義多個環境,以下所示:web
<profiles> <!--平常開發環境--> <profile> <id>test</id> <properties> <profileActive>test</profileActive> </properties> </profile> <!--預發佈環境--> <profile> <id>dev</id> <properties> <profileActive>dev</profileActive> </properties> </profile> <!--線上環境--> <profile> <id>prod</id> <properties> <profileActive>prod</profileActive> <!--<package.environment>prod</package.environment>--> </properties> </profile> </profiles>
在build中定義resources資源打包規則,以下所示:數據庫
<resources> <resource> <!--指定打包時,須要特殊處理的文件路徑--> <directory>src/main/resources</directory> <!--處理文件時,須要對文件進行變量替換--> <filtering>true</filtering> <excludes> <!--指定打包時,不包含如下文件--> <exclude>application-dev.properties</exclude> <exclude>application-prod.properties</exclude> <exclude>application-test.properties</exclude> <exclude>application.properties</exclude> </excludes> </resource> <resource> <filtering>true</filtering> <directory>src/main/resources</directory> <includes> <include>application-${profileActive}.properties</include> <include>application.properties</include> </includes> </resource> <resource> <directory>src/main/java</directory> <filtering>false</filtering> </resource> </resources>
mvn clean
清理上次編譯的target文件;mvn package
打包項目,能夠看到application.properties和application-dev.properties;mvn clean package -Dmaven.test.skip=true -P dev -e
打包項目。結果和步驟3一致。src -main –bin 腳本庫 –java java源代碼文件 –resources 資源庫,會自動複製到classes目錄裏 –filters 資源過濾文件 –assembly 組件的描述配置(如何打包) –config 配置文件 –webapp web應用的目錄。WEB-INF、css、js等 -test –java 單元測試java源代碼文件 –resources 測試須要用的資源庫 –filters 測試資源過濾庫 -site Site(一些文檔) target LICENSE.txt Project’s license README.txt Project’s readme