首页 > 解决方案 > 在 OSGi DS 服务上使用 @Reference 时组件创建失败

问题描述

我正在尝试在 DS 组件上调用绑定/取消绑定方法。我已将其简化为最简单但不起作用的示例。

如果我删除了 bind 方法上的 @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
    }
}

标签: osgieclipse-rcpdeclarative-services

解决方案


您的组件正试图将自己用作依赖项。因此,您有一个无法解决的循环引用。在满足对 Foo 服务(@Reference)的依赖之前,无法满足您的组件(因此注册为 Foo 服务)。


推荐阅读