利用 ManagedService 介面來接收配置資料
Liberty 配置由「OSGi 配置管理」服務來管理,可以根據「OSGi 配置管理」服務規格來進行存取。配置內容集是利用持續身分 (PID) 來識別,這個身分用來將 server.xml 檔中的元素(以 PID 為元素名稱)關聯於為了接收內容而登錄的元件。
關於這項作業
對於利用 BundleActivator 介面來管理其生命週期的 OSGi 軟體組而言,實作 org.osgi.service.cm.ManagedService 介面,指定 PID 為其中一項內容,是接收配置內容的一個直接而明確的方法。
範例
記住:
在 Eclipse 中,您必須從
,選取 SPI 目標執行時期。- 在 MANIFEST.MF 檔中新增下列陳述式:
Import-Package: org.osgi.service.cm;version="1.5.0"
- 按 Ctrl + Shift + O,以更新您的軟體組啟動器。
在這個範例中,除了 BundleActivator 介面,Activator 類別還實作 ManagedService 介面,利用 updated 方法來接收配置內容。 您可以提供預設內容值來簡化使用者配置所需指定的項目。
public class Activator implements BundleActivator, ManagedService {
public void start(BundleContext context) throws Exception {
System.out.println("Sample bundle starting");
// register to receive configuration
ServiceRegistration<ManagedService> configRef = context.registerService(
ManagedService.class,
this,
getDefaults()
);
}
public void stop(BundleContext context) throws Exception {
System.out.println("Sample bundle stopping");
configRef.unregister();
}
Hashtable getDefaults() {
Hashtable defaults = new Hashtable();
defaults.put(org.osgi.framework.Constants.SERVICE_PID, "simpleBundle");
return defaults;
}
public void updated(Dictionary<String, ?> properties) throws ConfigurationException {
if (properties != null)
{
String configColor = (String) properties.get("color");
String configFlavor = (String) properties.get("flavor");
}
}
}
軟體組的使用者配置是通過下列項目,選擇性地在 server.xml 檔或某個併入檔中提供:
<simpleBundle color="red" flavor="raspberry" />
註: 使用者配置中的元素名稱 simpleBundle 符合 ManagedService 登錄中所用的 org.osgi.framework.Constants.SERVICE_PID 內容。
如果是更進階的配置用法,請參閱利用 OSGi meta 類型服務說明配置。