Spring 應用隨規模增長,單一 applicationContext.xml 會膨脹難維護。模組化拆分多配置檔是必然選擇。本文整理 Spring 載入多配置檔的三種標準方式。
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "a1.xml", "a2.xml", "dao.xml", "service.xml" }
);
// 載入 classpath 根目錄所有 applicationContext-*.xml
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-*.xml");
// 載入特定目錄下所有 xml
ApplicationContext context = new ClassPathXmlApplicationContext("config/*.xml");
<import> 標籤在主配置檔匯入 (官方推薦)主配置檔 applicationContext.xml:
classpath: 前綴、JAR 內檔案同樣支援、IDE 可導航跳轉BeanDefinitionParsingExceptionweb.xml 僅載入主配置檔
contextConfigLocation
/WEB-INF/applicationContext.xml
org.springframework.web.context.ContextLoaderListener
ContextLoaderListener 讀取 contextConfigLocation,載入主配置檔,主配置檔透過 <import> 遞歸匯入所有子模組配置。
-Dspring.profiles.active=prod
| 場景 | 推薦方式 |
|---|---|
| 單元測試、獨立主程式 | 方式一 (String[]) |
| 約定目錄結構、非 JAR 部署 | 方式二 (通配符) |
| 企業級 Web/EE 應用、JAR 模組化 | 方式三 (<import>) ✓ 最佳實踐 |
| 多環境部署 | 方式三 + Spring Profile |