同一套代碼部署到開發、測試、生產環境,數據庫連接、Redis 地址、日志級別、三方服務 URL 全不同。手動改配置文件易出錯、版本難管理、洩露敏感信息風險高。
Maven Profile 允許在 pom.xml 中定義多組 <properties>,通過 -P 參數激活不同 Profile,構建時將對應屬性值注入資源文件 (開啟 <filtering>true</filtering>),實現「一份代碼、多環境構建」。
<profiles>
<profile>
<id>dev</id>
<properties>
<profiles.active>dev</profiles.active>
<db.url>jdbc:mysql://dev-db:3306/app?useSSL=false</db.url>
<db.user>dev_user</db.user>
<db.pwd>dev_pwd</db.pwd>
</properties>
<activation>
<activeByDefault>true</activeByDefault> <!-- 默認激活 -->
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<profiles.active>test</profiles.active>
<db.url>jdbc:mysql://test-db:3306/app</db.url>
<db.user>test_user</db.user>
<db.pwd>test_pwd</db.pwd>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<profiles.active>prod</profiles.active>
<db.url>jdbc:mysql://prod-db:3306/app</db.url>
<db.user>${env.DB_USER}</db.user> <!-- 敏感值從環境讀取 -->
<db.pwd>${env.DB_PWD}</db.pwd>
</properties>
</profile>
</profiles>
# 通用配置 app.name=MyApp server.port=8080 # 環境相關佔位符,構建時自動替換 spring.datasource.url=@db.url@ spring.datasource.username=@db.user@ spring.datasource.password=@db.pwd@ # 日志級別 logging.level.root=@log.level@
💡 Spring Boot 默認用
@...@作為佔位符分隔符,避免與${...}衝突。Maven 默認用${...},需在maven-resources-plugin配置<delimiters><delimiter>@</delimiter></delimiters>。
src/main/resources/ ├── application.properties # 通用+佔位符 ├── application-dev.properties # 開發環境覆蓋 ├── application-test.properties # 測試環境覆蓋 └── application-prod.properties # 生產環境覆蓋
Spring Boot 啟動時自動加載 application-{active}.properties 覆蓋基礎配置,無需 Maven 過濾也能實現多環境,但敏感信息仍建議用環境變量/配置中心。
<build>
<filters>
<filter>src/main/resources/config/application-${profiles.active}.properties</filter>
</filters>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering> <!-- 關鍵:啟用佔位符替換 -->
<includes>
<include>**/*.properties</include>
<include>**/*.yml</include>
<include>**/*.xml</include>
</includes>
</resource>
<!-- 排除不需過濾的二進制文件 -->
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<excludes>
<exclude>**/*.png</exclude>
<exclude>**/*.jpg</exclude>
</excludes>
</resource>
</resources>
</build>
方案 適用場景 優點 缺點 Maven Profile 單體應用、構建期區分 原生支持、無額外依賴 需重新打包、敏感信息難管理 Spring Profile + application-{env}.properties Spring Boot 應用、啟動期區分 熱加載友好、IDE 直接切換 配置文件隨包體分發、敏感信息風險 配置中心 微服務、動態變更、敏感信息隔離 實時生效、權限控制、審計日志 引入基礎設施複雜度