问题描述
我正在尝试在 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
}
}
解决方法
您的组件正试图将自身用作依赖项。因此,您有一个无法解决的循环引用。在满足对 Foo 服务(@Reference)的依赖之前,您的组件无法满足(因此注册为 Foo 服务)。