4

我在我的应用程序中使用嵌入式 Felix。应用程序可能会处理许多公开类似接口的插件IFoo。有一个默认实现FooImpl希望大多数插件默认FooImpl可以与特定的配置文件一起使用。

FooImpl当新的配置文件出现时,我想动态安装并启动同一个包(使用)。我已经查看过 FileInstall,但不知道如何在那里应用它。

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

4

2 回答 2

7

使用工厂配置将允许您基于不同的配置创建不同的 FooImpl 实例。

例如,在声明式服务中,您可以创建一个组件,如

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();
        }
    }
}

这里的关键点是

  1. 您使用类型的组件configurationFactory
  2. 在激活方法中,您读取配置,然后基于该注册服务
  3. 在停用时,您明确取消注册服务
  4. 然后,最终用户将使用 name 创建配置文件<pid>-<some name>.cfg。然后 DS 将激活该组件。

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

有关此类示例,请参阅JdbcLoginModuleFactory及其相关配置

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

这里的关键点是

  1. 您使用配置 PID 注册一个 ManagedServiceFactory 实例作为服务属性
  2. 在 ManagedServiceFactory(String pid, Dictionary properties) 回调中根据配置属性注册 FooImpl 的实例
于 2013-04-08T05:52:21.367 回答
1

听起来您只想安装一个带有 FooImpl 的捆绑包,但让它注册多个 IFoo 服务,每个配置一个。查看声明式服务并使用带有 Config Admin 的工厂配置来为 DS 组件建立多个配置。

于 2013-04-06T13:20:18.130 回答