Spring Boot 2 多模塊項目中配置文件的加載順序
在 Spring Boot 2 多模塊項目中,配置文件的加載遵循特定的順序規則。了解這些規則對于正確管理多模塊應用的配置至關重要。
一、默認配置文件加載順序
Spring Boot 會按照以下順序加載 application.properties
或 application.yml
文件:
-
當前模塊的
config
目錄 (位于 classpath 根目錄下)classpath:/config/application.properties
classpath:/config/application.yml
-
當前模塊的根目錄
classpath:/application.properties
classpath:/application.yml
-
父模塊的
config
目錄 (如果存在依賴關系)classpath:/../config/application.properties
(相對路徑)classpath:/../config/application.yml
-
父模塊的根目錄
classpath:/../application.properties
classpath:/../application.yml
二、多模塊項目中的特殊加載規則
1. 模塊間配置繼承
- 子模塊會自動繼承父模塊的配置
- 子模塊的配置會覆蓋父模塊的同名配置
- 使用
spring.config.import
可以顯式導入其他模塊的配置
2. Profile 特定的配置
對于 application-{profile}.properties/yml
文件:
- 加載順序與主配置文件相同
- Profile 配置會覆蓋主配置
3. 外部化配置加載順序
除了 classpath 內的配置,Spring Boot 還會按以下順序加載外部配置:
- 當前目錄的
/config
子目錄 - 當前目錄
- classpath 的
/config
包 - classpath 根目錄
三、多模塊配置管理最佳實踐
1. 推薦的項目結構
parent-module/
├── common-module/ # 公共模塊
│ └── src/main/resources/
│ ├── application.yml # 公共基礎配置
│ └── application-{profile}.yml
├── service-module/ # 業務模塊
│ └── src/main/resources/
│ ├── application.yml # 模塊特有配置
│ └── application-{profile}.yml
└── web-module/ # Web模塊└── src/main/resources/├── application.yml└── application-{profile}.yml
2. 配置覆蓋示例
父模塊 (common) application.yml:
server:port: 8080
spring:datasource:url: jdbc:mysql://localhost:3306/common_db
子模塊 (web) application.yml:
server:port: 8081 # 覆蓋父模塊的端口配置
spring:datasource:url: jdbc:mysql://localhost:3306/web_db # 覆蓋數據源配置
3. 顯式導入配置
Spring Boot 2.4+ 支持使用 spring.config.import
:
# service-module 的 application.yml
spring:config:import:- classpath:application-common.yml # 導入公共配置- optional:classpath:application-override.yml # 可選導入
四、調試配置加載順序
1. 查看生效的配置
啟動應用時添加參數:
java -jar your-app.jar --debug
或在日志中設置:
logging:level:org.springframework.boot.context.config: TRACE
2. 查看 PropertySources
在應用中注入并輸出:
@Autowired
private ConfigurableEnvironment env;@PostConstruct
public void printProperties() {env.getPropertySources().forEach(ps -> {System.out.println("PropertySource: " + ps.getName());});
}
五、常見問題解決方案
1. 配置不生效
- 檢查文件位置是否正確
- 確認文件名拼寫(注意
application
的全小寫) - 檢查模塊依賴是否正確
2. Profile 配置未加載
- 確保激活了正確的 profile:
java -jar your-app.jar --spring.profiles.active=dev
3. 多模塊配置沖突
- 使用前綴區分不同模塊的配置:
# common 模塊 common:datasource:url: jdbc:mysql://localhost/common# web 模塊 web:datasource:url: jdbc:mysql://localhost/web
通過合理組織多模塊項目的配置文件,可以確保配置的正確加載和覆蓋,同時保持各模塊配置的清晰性和可維護性。