【问题标题】:Working with configs using pure OSGi interfaces with ManagedService使用带有 ManagedService 的纯 OSGi 接口处理配置
【发布时间】:2014-04-19 13:29:26
【问题描述】:

我正在开发 OSGI 包。我已经实现了一个 BundleActivator,这是我的代码。

public class Activator implements BundleActivator {
private static final String CONFIG_PID = "ConfigApp";
private ServiceRegistration serviceReg;
public VfsDAO app;

@Override
public void start(BundleContext context) throws Exception {

    System.out.println("Hello................ bundle started");
    Hashtable<String, Object> properties = new Hashtable<String, Object>();
    properties.put(Constants.SERVICE_PID, CONFIG_PID);
    serviceReg = context.registerService(ManagedService.class.getName(), new ConfigUpdater() , properties);

}

@Override
public void stop(BundleContext context) throws Exception {
    serviceReg.unregister();
}

/**
 * Updates the configuration in the application. Of course your class can also directly implement ManagedService but this
 * way you can work with pojos
 */
private final class ConfigUpdater implements ManagedService {
    @SuppressWarnings("rawtypes")
    @Override
    public void updated(Dictionary config) throws ConfigurationException {
        if (config == null) {
            return;
        }
        if (app == null) {
            app = new VfsDAO();
        }
        app.setAllowed((String)config.get("title"));
        System.out.println("FROM................ bundle ACTIVATOR");
        app.refresh();
    }
}

}

现在,如果我在任何其他类中创建 VfsDAO() 对象,则不会调用 setAllowed,因此未初始化允许的字符串。当我在任何其他类中创建新的 VfsDAO() 对象时,如何获取该值?或者当我在任何其他允许的类字符串中创建 VfsDAO() 的新对象时,我如何在 VfsDAO 类中调用 (String)config.get("title") 。

【问题讨论】:

    标签: osgi osgi-bundle


    【解决方案1】:

    为了让 OSGi 在配置更改时通知您的 VfsDAO,它必须由 OSGi 运行时以某种方式进行管理。您上面的代码通过充当围绕您的 VfsDAO 的 OSGi 托管服务包装器来完成此操作。如果您在代码中的某些地方使用new VfsDAO(),并且您没有像上面的示例中那样包装生命周期管理(或者与 OSGi 有一些其他生命周期绑定),那么 OSGi 将无法知道您的代码创建了一个 VfsDAO。

    如果您需要多个 VfsDAO 实例,可能配置有不同的 allowed 属性,我建议使用 OSGi ManagedServiceFactory。使用托管服务工厂,您将改为创建多个 VfsDAO 实例,每个实例都有自己的 PID 和通过 ConfigAdmin 的配置。

    【讨论】:

      猜你喜欢
      • 2011-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      • 2018-01-26
      • 1970-01-01
      相关资源
      最近更新 更多