Dependency injection 在非组件类中注入OSGi服务

Dependency injection 在非组件类中注入OSGi服务,dependency-injection,osgi,Dependency Injection,Osgi,通常我在OSGi开发中看到一个服务绑定到另一个服务。然而,我试图在非服务类中注入OSGi服务 尝试实现的场景:我实现了一个MessageBusListener,它是一个OSGi服务,并绑定到多个服务,如QueueExecutor等 现在MessageBusListener的任务之一是创建一个FlowListener(非服务类),它将根据消息内容调用流。此FlowListener需要诸如QueueExecutor之类的OSGi服务来调用流 我尝试的方法之一是在从MessageBusListener

通常我在OSGi开发中看到一个服务绑定到另一个服务。然而,我试图在非服务类中注入OSGi服务

尝试实现的场景:我实现了一个MessageBusListener,它是一个OSGi服务,并绑定到多个服务,如QueueExecutor等

现在MessageBusListener的任务之一是创建一个FlowListener(非服务类),它将根据消息内容调用流。此FlowListener需要诸如QueueExecutor之类的OSGi服务来调用流

我尝试的方法之一是在从MessageBusListener创建FlowListener实例时传递服务的引用。然而,当参数化服务被停用并重新激活时,我认为OSGi服务将创建一个新的服务实例并绑定到MessageBusListener,但是FlowListener仍然会有一个过时的引用

@Component
public class MessageBusListener
{
    private final AtomicReference<QueueExecutor> queueExecutor = new AtomicReference<>();

    @Activate
    protected void activate(Map<String, Object> osgiMap)
    {
        FlowListener f1 = new FlowListener(queueExeciutor)
    }

    Reference (service = QueueExecutor.class, cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC)
    protected void bindQueueExecutor(QueueExecutor queueExecutor)
    {
        this.queueExecutor = queueExecutor;
    }
}

public class FlowListener
{
    private final AtomicReference<QueueExecutor> queueExecutor;

    FlowListener(QueueExecutor queueExecutor)
    {
        this.queueExecutor = queueExecutor;
    }
    queueExecutor.doSomething() *// This would fail in case the QueueExecutor 
    service was deactivated and activated again*
}
@组件
公共类MessageBusListener
{
private final AtomicReference queueExecutor=新的AtomicReference();
@激活
受保护的无效激活(映射osgiMap)
{
FlowListener f1=新的FlowListener(队列执行器)
}
引用(服务=QueueExecutor.class,基数=ReferenceCardinality.MANDATORY,策略=ReferencePolicy.STATIC)
受保护的无效bindQueueExecutor(QueueExecutor QueueExecutor)
{
this.queueExecutor=queueExecutor;
}
}
公共类流侦听器
{
私有最终原子引用队列执行器;
FlowListener(队列执行器队列执行器)
{
this.queueExecutor=queueExecutor;
}
queueExecutor.doSomething()*//如果queueExecutor
服务已停用并再次激活*
}

期待其他方法,可以满足我的要求

您的方法是正确的,您只需在必要时处理停用

如果QueueExecutor消失,MessageBuslistener将关闭。您可以使用@Deactivate方法处理此问题。在这个方法中,您还可以调用FlowListener的sutdown方法

如果出现一个新的QUEExecutor服务,那么DS将创建一个新的MessageBuslistener,这样一切都会好起来

顺便说一句,您可以使用以下方法简单地注入QueueExecutor:

@Reference
QueueExecutor queueExecutor;

是的,我也想到了这种方法。与MessageBusListener一样,MessageBusListener可以跟踪所有创建的FlowListener,一旦停用,它可以销毁现有的FlowListener。然而,创建和销毁将是一个更复杂的计算过程。我想公开OSGi是否提供了处理这种情况的能力。。因此,有几个QueueExecutor服务,您希望每个服务都有一个FlowListener?不。将有一个OSGi定义的属性,称为Queues(将在激活/修改MessageBusListener期间随osgiMap出现)。此属性将以逗号分隔,提供队列地址。因此,对于每个队列地址,将有一个新的专用FlowListener。我认为在本例中,我将在MessageBuslistener中管理FlowListener实例的映射。