使用 ManagedService 接口来接收配置数据

Liberty 配置由 OSGi 配置管理服务管理,并且可以根据 OSGi 配置管理服务规范来访问此配置。配置属性集由持久存储的身份 (PID) 来标识,其中 PID 用作元素名称,且用于将 server.xml 文件中的元素与注册用来接收属性的组件相关联。

关于此任务

对于使用 BundleActivator 接口来管理其生命周期的 OSGi 捆绑软件,接收配置属性的直观方式是实现 org.osgi.service.cm.ManagedService 接口,该接口指定 PID 作为其属性。

示例

切记:
  1. 在 Eclipse 中,必须从窗口 > 首选项 > 插件开发 > 目标平台选择 SPI 目标运行时。

  2. 将以下语句添加至 MANIFEST.MF 文件:
    Import-Package: org.osgi.service.cm;version="1.5.0"
  3. 按 Ctrl + Shift + O 以更新捆绑软件激活器。

在此示例中,Activator 类实现 ManagedService 接口及 BundleActivator 接口,并使用 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" />
注: 用户配置中的元素名称 simpleBundleManagedService 注册中使用的 org.osgi.framework.Constants.SERVICE_PID 属性的值相匹配。

有关更高级的配置用法,请参阅使用 OSGi 元类型服务来描述配置


用于指示主题类型的图标 任务主题



时间戳记图标 最近一次更新时间: Monday, 5 December 2016
http://www14.software.ibm.com/webapp/wsbroker/redirect?version=cord&product=was-libcore-mp&topic=twlp_receive_config_data_managedservice
文件名:twlp_receive_config_data_managedservice.html