【问题标题】:Is it possible to create OSGI Service programmatically with Injections resolved是否可以通过解决注入以编程方式创建 OSGI 服务
【发布时间】:2017-10-02 20:29:50
【问题描述】:

不幸的是,我找不到通过已解析引用以编程方式创建 osgi 服务的方法。众所周知,OSGi 将服务创建为单例对象。由于某种原因,我需要手动创建新的服务实例。

案例:

@Service(ICasualService.class)
@Component(immediate = true, label = "Casual Service")
public class CasualService implements ICasualService {

    @Reference
    private ConfigurationAdmin configurationAdmin;
}

使用 Bundle Context 我可以注册我的服务:

private BundleContext bundleContext;
ICasualService casualService = new CasualService();  
Dictionary props = new Properties();
bundleContext.registerService(ICasualService.class.getName(), casualService, props);

但是,这种方式 configurationAdmin 在新创建的服务中为空。

问题是是否可以通过编程方式创建服务的新实例?

谢谢。

更新:解决方案应该适用于 Felix(OSGi 实现)。

【问题讨论】:

    标签: java osgi aem apache-felix


    【解决方案1】:

    您可以使用 ComponentFactory 来创建组件的实例。见this article at Vogella

    在您要以编程方式创建的组件上使用它:

    @Component(factory="fipro.oneshot.factory")
    

    然后在另一个组件中你可以得到 ComponentFactory:

    @Reference(target = "(component.factory=fipro.oneshot.factory)")
        private ComponentFactory factory;
    

    并从中创建一个实例:

    ComponentInstance instance = this.factory.newInstance(null);
    OneShot shooter = (OneShot) instance.getInstance();
    

    【讨论】:

    • 非常感谢!有用。此外, 1. 这样,您可以通过将它们传递给 this.factory.newInstance(Dictionary) 方法来创建具有适当配置参数的新服务; 2. 创建新的服务实例(如果 .newInstance(null) 每次返回相同的对象)。
    猜你喜欢
    • 2015-04-12
    • 2015-02-06
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    相关资源
    最近更新 更多