前提
項目常見的部署環境:Dev(開發環境)、Test(測試環境)、Proc(生產環境)
問題
不同環境配置文件的配置往往需要進行一些修改,如果配置文件只有一份且打包在war中,那么在其他環境下就需要進行對應的修改。站在部署的角度,這將會變得非常的不方便。
解決方法
可以通過maven pom.xml提供的 profiles標簽 來實現 打包時 指定何種環境的配置文件
步驟
1.在pom.xml中添加 profiles 信息
<profiles>
<profile>
<!--id唯一,打包時可以通過 -P profile.id 指定profile-->
<id>Dev</id>
<properties>
<!--自定義標簽,等待被${}占位符引用-->
<profile.active>Dev</profile.active>
</properties>
<activation>
<!--打包時不指定profile,默認使用-->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>Test</id>
<properties>
<profile.active>Test</profile.active>
</properties>
</profile>
<profile>
<id>Proc</id>
<properties>
<profile.active>Proc</profile.active>
</properties>
</profile>
</profiles>
2.排除內部的配置文件,使用占位符傳參方式指定profile.id,此處可以使用兩種方式
- 1.將所有環境的配置文件全放在項目(war)中。配置簡單
- 2.將配置文件放在項目(war)外,使用 系統環境變量 指定配置文件夾位置。更靈活,修改外部的文件重新打包即可
第一種方式比較常見,這里不多贅述
3.使用第二種方式實現
環境變量配置如下:

pom.xml中,加入對resources處理。排除內部配置文件,引用外部配置文件(當然,也可以直接將內部配置文件直接移除)
<resources>
<resource>
<directory>src/main/resources/</directory>
<!--排除內部配置文件,不進行打包-->
<excludes>
<exclude>db.properties</exclude>
<exclude>config.properties</exclude>
</excludes>
</resource>
<resource>
<!--${ENV_SETTING_HOME}為環境變量,maven中可直接使用${}的方式引用環境變量-->
<!--${profile.active}為 profile的具體值-->
<directory>/${ENV_SETTING_HOME}/${profile.active}</directory>
</resource>
</resources>
4.進行打包,指定 profile.id
打包命令行:mvn clean package -P Dev|Test|Proc
使用eclipse有兩種方式(其實只是簡化了命令行),如下:


