OSGi强制捆绑包以不同的配置启动两次

Dew*_*wfy 4 osgi apache-felix

我在我的应用程序中使用嵌入式Felix.应用程序可能会处理暴露类似接口的大量插件IFoo.默认情况下,实现FooImpl希望大多数插件默认FooImpl可以与特定配置文件一起使用.

我希望FooImpl在出现新配置文件时动态安装并启动相同的bundle(with ).我已经审查过FileInstall,但不知道如何在那里应用它.

更新:部署顺序.jar包含FooImplIFoo稳定,但我需要热部署新的实例,这些实例是将新的.cfg文件上传到FileInstall的范围.所以非常简单 - 用户上传.cfg,新服务(实例FooImpl)出现了.

Che*_*tan 7

使用Factory Configurations可以根据不同的配置创建不同的FooImpl实例.

例如,在Declarative Services中,您可以创建一个类似的组件

import org.apache.felix.scr.annotations.*;
import org.apache.sling.commons.osgi.PropertiesUtil;

@Component(metatype = true, 
        name = FooImpl.SERVICE_PID,
        configurationFactory = true, 
        specVersion = "1.1",
        policy = ConfigurationPolicy.REQUIRE)
public class FooImpl implements IFoo
{
    //The PID can also be defined in interface
    public static final String SERVICE_PID = "com.foo.factory";

    private static final String DEFAULT_BAR = "yahoo";
    @Property
    private static final String PROP_BAR = "bar";

    @Property(intValue = 0)
    static final String PROP_RANKING = "ranking";

    private ServiceRegistration reg;

    @Activate
    public void activate(BundleContext context, Map<String, ?> conf)
        throws InvalidSyntaxException
    {
        Dictionary<String, Object> props = new Hashtable<String, Object>();
        props.put("type", PropertiesUtil.toString(config.get(PROP_BAR), DEFAULT_BAR));
        props.put(Constants.SERVICE_RANKING,
            PropertiesUtil.toInteger(config.get(PROP_RANKING), 0));
        reg = context.registerService(IFoo.class.getName(), this, props);
    }

    @Deactivate
    private void deactivate()
    {
        if (reg != null)
        {
            reg.unregister();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

关键点在这里

  1. 您使用类型的组件 configurationFactory
  2. 在activate方法中,您可以读取配置,然后根据该寄存器获取服务
  3. 在停用时,您明确取消注册该服务
  4. 然后,最终用户将使用名称创建配置文件<pid>-<some name>.cfg.然后DS会激活该组件.

然后,您可以通过创建名称<pid>-<some name>.cfg类似的配置(使用File Install like)来创建多个实例com.foo.factory-type1.cfg

有关此类示例,请参阅JdbcLoginModuleFactory及其关联的配置.

如果你想通过普通的OSGi实现相同的功能,那么你需要注册一个ManagedServiceFactory.有关此类示例,请参阅JaasConfigFactory.

关键点在这里

  1. 您使用配置PID作为服务属性注册ManagedServiceFactory实例
  2. 在ManagedServiceFactory(String pid,Dictionary属性)中基于配置属性的FooImpl回调寄存器实例