【问题标题】:Component creation fails when using @Reference on OSGi DS service在 OSGi DS 服务上使用 @Reference 时组件创建失败
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 好的,有道理。在组件上指定绑定/取消绑定方法的正确方法是什么?
    【解决方案2】:

    我的问题的答案是,在 1.3 规范中,使用 @Activate 和 @Deactivate。我已经修改了原始问题以在代码中显示解决方案。

    查看http://blog.vogella.com/2016/06/21/getting-started-with-osgi-declarative-services/了解更多详情。

    【讨论】:

      猜你喜欢
      • 2020-06-08
      • 2016-05-15
      • 2020-12-31
      • 1970-01-01
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2010-11-09
      相关资源
      最近更新 更多