【发布时间】:2019-04-18 13:26:53
【问题描述】:
假设我有以下 OSGi 组件,它应该在每次在运行时注册 SomeInterface 的新实现时发送一个事件。
为此,我将EventAdmin 绑定到eventAdmin 变量中,然后在bindSomeInterface 方法中使用它。
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
@Component
public class Sender {
private EventAdmin eventAdmin;
@Reference
public void bindEventAdmin(EventAdmin eventAdmin) {
this.eventAdmin = eventAdmin;
}
public void unbindEventAdmin(EventAdmin eventAdmin) {
this.eventAdmin = null;
}
@Reference(cardinality = ReferenceCardinality.MULTIPLE)
public void bindSomeInterface(SomeInterface instance) {
// var prop create here... (non relevant code)
Event event = new Event("topic", prop);
// it is NULL!
eventAdmin.sendEvent(event);
}
public void unbindSomeInterface(SomeInterface instance) {
}
}
生成的xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="com.package.Sender">
<reference bind="bindSomeInterface" cardinality="0..n" interface="com.package.bindSomeInterface" name="SomeInterface" policy="static" unbind="unbindSomeInterface"/>
<reference bind="bindEventAdmin" interface="org.osgi.service.event.EventAdmin" name="EventAdmin" policy="static" unbind="unbindEventAdmin"/>
<implementation class="com.package.Sender"/>
</scr:component>
问题
bindSomeInterface 首先被调用(得到一个“通知”,SomeInterface 的新实例已在运行时注册),然后bindEventAdmin 被调用。这不是我们想要的效果。
预期行为
我想先绑定EventAdmin 实例,然后绑定SomeInterface 实例。
我该怎么做?
非常接近的问题(但不一样):Bind order of OSGi declarative services
PS:我试图避免ServiceTrakers 之类的东西。
【问题讨论】: