使用带有ManagedService的纯OSGi接口处理配置

使用带有ManagedService的纯OSGi接口处理配置,osgi,osgi-bundle,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 c

我正在开发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();
    }
}

}
公共类激活器实现BundleActivator{
私有静态最终字符串CONFIG_PID=“ConfigApp”;
私人服务注册服务注册;
公共VfsDAO应用程序;
@凌驾
public void start(BundleContext)引发异常{
System.out.println(“你好…………捆绑启动”);
Hashtable属性=新的Hashtable();
properties.put(Constants.SERVICE\u PID,CONFIG\u PID);
serviceReg=context.registerService(ManagedService.class.getName(),new ConfigUpdater(),properties);
}
@凌驾
公共void stop(BundleContext上下文)引发异常{
serviceReg.unregister();
}
/**
*更新应用程序中的配置。当然,您的类也可以直接实现ManagedService,但是
*你能和波乔一起工作的方式
*/
私有最终类ConfigUpdater实现ManagedService{
@抑制警告(“原始类型”)
@凌驾
已更新公共void(字典配置)引发ConfigurationException{
if(config==null){
返回;
}
如果(app==null){
app=新VfsDAO();
}
app.setAllowed((String)config.get(“title”);
系统输出打印项次(“来自……束激活器”);
app.refresh();
}
}
}

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

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

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