使用纯OSGi接口与ManagedService一起使用配置

时间:2014-04-19 13:29:26

标签: osgi osgi-bundle

我正在开发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,因此未初始化String允许的值。当我在任何其他类中创建新的VfsDAO()对象时,如何获取该值?或者如何在VfsDAO类中调用(String)config.get(“title”),以便在我允许的任何其他类字符串中创建VfsDAO()的新对象时启动。

1 个答案:

答案 0 :(得分:0)

为了让OSGi通知配置更改,VscDAO必须由OSGi运行时以某种方式进行管理。上面的代码通过充当VfsDAO的OSGi托管服务包装器来实现这一点。如果您在代码中的某些位置使用new VfsDAO()并且您不像上面的示例那样包装生命周期管理(或者与OSGi有其他生命周期绑定),那么将会OSGi无法知道您的代码是否创建了VfsDAO。

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