補上可比較的配置與啟動命令,說明 profile 不會自動在兩種工具間同步。
適用:保留原 Spring/Spring Boot 歷史筆記;可重現練習統一採 Spring Boot 3.5.16、JDK 25 與 Maven,使用 jakarta 套件。編譯目標為 Java 25;上線仍需核對依賴及部署環境。
先備:先依 共用 Spring Boot 練習專案 建立 pom.xml 與 NoteApplication,再加入本文檔案。
兩種Profile
Maven profile在建置時選依賴、plugin或property,Spring profile在應用context建立時選設定與bean。同名dev也不會自動連動;要連動必須明確寫filter或plugin引數,並注意是否把環境內容烘進jar。
共用專案的src/main/resources/application.properties:
notes.banner=defaultapplication-dev.properties:
notes.banner=development新增BannerConfig.java:
package notes;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class BannerConfig {
@Bean
CommandLineRunner showBanner(@Value("${notes.banner}") String banner) {
return args -> System.out.println("notes.banner=" + banner);
}
}執行確認
mvn package
java -jar target/spring-note-lab-1.0.0.jar --spring.profiles.active=dev日誌應包含notes.banner=development。不指定dev則default。JVM系統引數寫在-jar之前,如java -Dspring.profiles.active=dev -jar ...;寫在jar後是應用引數,不是JVM引數。
Maven可在pom profiles定義id後用mvn -Pdev help:active-profiles確認;僅加-Pdev不會啟用Spring dev。部署可使用OS SPRING_PROFILES_ACTIVE或命令引數,但屬性優先順序需按Boot文件核對,同一key不要散落多個來源。
常見問題
spring.profiles.active不放在已由profile啟用的專屬檔案內遞迴決定自身。profile不是秘密管理系統,勿提交prod密碼。Config Data/Spring Cloud bootstrap機制在不同major有變化,新專案按所用版本選spring.config.import,不複製舊bootstrap.yml當通用配置。
參考資料
- Spring profiles
- 外部配置
- Maven profiles
- Spring Profiles | Baeldung
- Spring profiles or Maven profiles? (frankel.ch)
- 深入淺出 Spring Boot 多重設定檔管理 (Spring Profiles) | The Will Will Web (miniasp.com)
- 菜鳥工程師 肉豬: Spring Boot 依環境設定不同的properties檔 Use different application.properties (matthung0807.blogspot.com)
- 54. Properties & configuration (spring.io)
冒險者留言
comments powered by Disqus