Spring-OSGi(後更名為 Spring Dynamic Modules)讓 Spring 應用上下文能在 OSGi 容器中自然運行。本文提煉 1.0 M3 版手冊精華,聚焦擴展點識別機制、必需 Bundle、包導入導出規約及配置最佳實踐。
Extender 在 Bundle 啟動時自動創建 Application Context,滿足任一條件即可:
META-INF/spring/ 目錄且包含至少一個 .xml 文件。META-INF/MANIFEST.MF 包含 Spring-Context 清單頭。若同時聲明 SpringExtender-Version,Extender 會校驗版本範圍(語法遵循 OSGi 3.2.5 節)。無 Spring-Context 時,META-INF/spring/*.xml 全被視為配置文件,所有指令取默認值。
語法:Spring-Context: path(;path)*(;directive)*,符合 OSGi 3.2.3 節通用頭語法。
示例:Spring-Context: config/account-data-context.xml, config/account-security-context.xml
| 指令 | 默認值 | 說明 |
|---|---|---|
| create-asynchronously | true | false 時同步創建 Context(阻塞 OSGi 事件線程),錯誤拋出 FrameworkEvent.ERROR 但 Bundle 仍進入 ACTIVE。 |
| wait-for-dependencies | true | false 時不等待強制服務依賴,視為可選引用。 |
| timeout | 300 秒 | 等待強制依賴滿足的最長時間,wait-for-dependencies:=false 時忽略。 |
| publish-context | true | false 時不將 Application Context 發布為 OSGi 服務。 |
通配符示例:Spring-Context: osgi-*;create-asynchronously:=false
約定命名:modulename-context.xml(純 Spring Bean,無 OSGi 依賴)+ modulename-osgi-context.xml(引入/導出 OSGi 服務)。後者可選用 Spring DM OSGi Schema 作為頂級命名空間替代 beans。
遵循 OSGi 規範:
• 所有外部依賴包必須在 Import-Package 中聲明。
• 需對外暴露的類型所在包必須在 Export-Package 中聲明。
• 盡量使用版本範圍(如 org.springframework.core;version="[2.5,3.0)")提升彈性。
Spring-Context 明確指定配置文件,避免誤掃描。create-asynchronously:=true 避免阻塞框架線程。wait-for-dependencies:=false 配合超時控制,防啟動死鎖。publish-context:=false 隱藏內部 Context,僅通過服務接口對外暴露能力。