是否可以通过注入解决以编程方式创建 OSGI 服务

Is it possible to create OSGI Service programmatically with Injections resolved

不幸的是,我找不到以编程方式创建带有已解析引用的 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 实现)。

您可以使用 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();