ManagedService インターフェースによる構成データの受け取り
Liberty プロファイル構成は、OSGi Configuration Admin サービス によって管理され、OSGi Configuration Admin サービス仕様に従ってアクセス することができます。構成プロパティー・セットはパーシスト ID (PID) によって識別されます。PID を使用して、プロパティーを受け取るために登録されたコンポーネントに server.xml ファイル (ここで、パーシスト ID (PID) をエレメント名として使用) のエレメントを関連付けます。
このタスクについて
BundleActivator インターフェースを使用してライフサイクルを管理する OSGi バンドルの場合、 構成プロパティーを受け取る簡単な方法としては、プロパティーの 1 つとして PID を指定する org.osgi.service.cm.ManagedService インターフェースを実装します。
例
要確認:
Eclipse では、
から SPI ターゲット・ランタイムを選択する必要があります。- MANIFEST.MF ファイルに次のステートメントを追加します。
Import-Package: org.osgi.service.cm;version="1.5.0"
- Ctrl + Shift + O を押して、バンドル・アクティベーターを更新します。
この例で、Activator クラスは、BundleActivator インターフェースに加えて 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 Metatype サービスを使用した構成の記述』を参照してください。