【发布时间】:2021-04-03 19:33:20
【问题描述】:
我正在尝试在 DS 组件上调用绑定/取消绑定方法。我已将其简化为最简单但不起作用的示例。
如果我删除绑定方法上的@Reference,则测试成功。显然日志语句不会被调用。否则它会在 AssertNotNull 上失败。
关于我做错了什么有什么建议吗?向组件添加绑定/取消绑定方法的正确方法是什么?
更新了代码以显示正确的方法。
界面
public interface Foo {
public abstract String bar();
}
类
@Component(immediate = true, enabled = true, service = Foo.class, scope = ServiceScope.SINGLETON)
public class FooImpl implements Foo {
private final static Logger logger = LoggerFactory.getLogger(FooImpl.class);
@Override
public String bar() {
return "bar";
}
@Activate
public synchronized void bind() {
logger.debug(String.format("bind called for %s", this.getClass().getName()));
}
@Deactivate
public synchronized void unbind(Foo service) {
logger.debug(String.format("unbind called for %s", this.getClass().getName()));
}
}
生成的组件定义
<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.3.0" activate="bindFoo" deactivate="unbindFoo" enabled="true" immediate="true" name="com.vogelware.experiment.FooImpl">
<service scope="singleton">
<provide interface="com.vogelware.experiment.Foo"/>
</service>
<implementation class="com.vogelware.experiment.FooImpl"/>
</scr:component>
测试类
class FooTest {
@Test
void test() throws InterruptedException {
ServiceTracker<Foo, Foo> testTracker = new ServiceTracker<Foo, Foo>(Activator.getContext(), Foo.class, null);
testTracker.open();
testTracker.waitForService(500);
Foo user = testTracker.getService();
testTracker.close();
assertNotNull(user); <= fails here
}
}
【问题讨论】:
标签: osgi eclipse-rcp declarative-services