背景
最近換了個新公司接手了一個老項目,而後比較坑的是這個公司的項目都沒有沒有作多環境打包配置,每次發佈一個環境都要手動的去修改配置文件。今天正好有空就來配置下。web
解決這個問題的方式有不少,我這裏挑選了一個我的比較喜歡的方案,經過 maven profile 打包的時候按照部署環境打包不一樣的配置,下面說下具體的操做apache
配置不一樣環境的配置文件
創建對應的環境目錄,我這裏有三個環境分別是,dev/test/pro 對應 開發/測試/生產。建好目錄後將相應的配置文件放到對應的環境目錄中app
配置 pom.xml 設置 profile
這裏經過 activeByDefault
將開發環境設置爲默認環境。若是你是用 idea 開發的話,在右側 maven projects > Profiles 能夠勾選對應的環境。webapp
<profiles> <profile> <!-- 本地開發環境 --> <id>dev</id> <properties> <profiles.active>dev</profiles.active> </properties> <activation> <activeByDefault>true</activeByDefault> </activation> </profile> <profile> <!-- 測試環境 --> <id>test</id> <properties> <profiles.active>test</profiles.active> </properties> </profile> <profile> <!-- 生產環境 --> <id>pro</id> <properties> <profiles.active>pro</profiles.active> </properties> </profile> </profiles>
打包時根據環境選擇配置目錄
這個項目比較坑,他把配置文件放到了webapps/config
下面。因此這裏打包排除 dev/test/pro 這三個目錄時候,不能使用exclude
去排除,在嘗試用 warSourceExcludes
能夠成功。以前還試過 packagingExcludes
也沒有生效,查了下資料發現 packagingExcludes
maven 主要是用來過濾 jar 包的。maven
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.1.0</version> <configuration> <warSourceExcludes> config/test/**,config/pro/**,config/dev/** </warSourceExcludes> <webResources> <resource> <directory>src/main/webapp/config/${profiles.active}</directory> <targetPath>config</targetPath> <filtering>true</filtering> </resource> </webResources> </configuration> </plugin>
最後根據環境打包
## 開發環境打包 mvn clean package -P dev ## 測試環境打包 mvn clean package -P test ## 生產環境打包 mvn clean package -P pro
執行完後發現 dev 目錄下的文件已經打包到 config下ide
啓動項目
我在啓動項目的時候,死活啓動不了。後來對比了先後的 target 目錄發現子項目的 jar 包有些差別,通過屢次嘗試後。將全部子項目下 target
項目從新刪除 install
最後成功啓動。測試