本文為《你好,OSGi》系列第七部分。讀者已了解 Spring DM 定義、與 OSGi 關係及開發環境建置,現正式開始應用開發。
使用 Spring DM 建立簡單 Hello World 應用:啟動時輸出「Hello Spring World!!」,關閉時輸出「Goodbye Spring World!!」。
package com.javaworld.osgi.spring;
public class HelloWorld {
public void start() throws Exception {
System.out.println("Hello Spring World!! ");
}
public void stop() throws Exception {
System.out.println("Goodbye Spring World!!");
}
}
純粹 POJO,無實作介面或繼承超類。包含 start()(啟動調用)與 stop()(關閉調用)兩方法。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="hello" class="com.javaworld.osgi.spring.HelloWorld"
init-method="start" destroy-method="stop"/>
</beans>
宣告名為 hello 的 Bean,指向 HelloWorld 類別,init-method 為 start,destroy-method 為 stop。
作為 Eclipse OSGi 應用執行時,主控台將顯示「Hello Spring World!!」。原理:建立 META-INF/spring 資料夾並放入 helloworld.xml 即完成設定。Extender Bundle 啟動時發現該 Bundle 由 Spring 提供(含 Spring-Context Manifest 標頭或 META-INF/spring 下 XML 檔),載入設定建立應用程式語境,調用 Bean 的初始化方法 start();關閉時調用銷毀方法 stop()。
OSGi 在面向服務應用開發的適用性為其最引人注目功能。OSGi 服務平台運行基於 OSGi 服務建構的面向服務應用。服務為簡單 Java 物件,在一或多個介面名稱下發布。核心概念:來源 Bundle 在公共登記處導出服務,消費者搜尋實作特定介面的服務,綁定並使用。
構建複雜企業應用時極具價值。例:Web 應用可分為資料存取 Bundle(與資料庫互動、導出資料存取服務)與 Web 層 Bundle(導入服務顯示資料)。模組化架構讓服務更新極易:欲從慢速服務升級至快速服務,只需建立新資料存取服務替換舊服務,無需重啟應用。
下一節將構建面向服務的聯絡人管理應用,示範 Spring Bean 如何導出為 OSGi 服務,以及 OSGi 服務如何導入為 Spring Bean。