首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring-OSGi 1.0 M3 參考手冊核心筆記:擴展點、依賴與最佳實踐

     編輯:Java 相關知識

Spring-OSGi(後更名為 Spring Dynamic Modules)讓 Spring 應用上下文能在 OSGi 容器中自然運行。本文提煉 1.0 M3 版手冊精華,聚焦擴展點識別機制、必需 Bundle、包導入導出規約及配置最佳實踐。

Spring Extender 識別「Spring-powered」Bundle 的規則

Extender 在 Bundle 啟動時自動創建 Application Context,滿足任一條件即可:

  1. Bundle Classpath 下存在 META-INF/spring/ 目錄且包含至少一個 .xml 文件。
  2. META-INF/MANIFEST.MF 包含 Spring-Context 清單頭。

若同時聲明 SpringExtender-Version,Extender 會校驗版本範圍(語法遵循 OSGi 3.2.5 節)。無 Spring-Context 時,META-INF/spring/*.xml 全被視為配置文件,所有指令取默認值。

Spring-Context 清單頭詳解

語法:Spring-Context: path(;path)*(;directive)*,符合 OSGi 3.2.3 節通用頭語法。
示例:Spring-Context: config/account-data-context.xml, config/account-security-context.xml

指令

指令默認值說明
create-asynchronouslytruefalse 時同步創建 Context(阻塞 OSGi 事件線程),錯誤拋出 FrameworkEvent.ERROR 但 Bundle 仍進入 ACTIVE。
wait-for-dependenciestruefalse 時不等待強制服務依賴,視為可選引用。
timeout300 秒等待強制依賴滿足的最長時間,wait-for-dependencies:=false 時忽略。
publish-contexttruefalse 時不將 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。

必需 Bundle 清單

Spring DM 自身

  • org.springframework.osgi.extender
  • org.springframework.osgi.core
  • org.springframework.osgi.io

Spring Framework(2.5+ 發布包已為有效 Bundle)

  • org.springframework.core
  • org.springframework.context
  • org.springframework.beans
  • org.springframework.aop

依賴庫(隨 Spring DM 分發提供 OSGi 版本)

  • aopalliance
  • backport-util (JDK 1.4)
  • cglib-nodep
  • commons-logging (推薦 SLF4J 版本)

Import-Package / Export-Package 原則

遵循 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,僅通過服務接口對外暴露能力。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved