osgi - 在 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
}
}
解决方案
您的组件正试图将自己用作依赖项。因此,您有一个无法解决的循环引用。在满足对 Foo 服务(@Reference)的依赖之前,无法满足您的组件(因此注册为 Foo 服务)。
推荐阅读
- .net - Zip 文件的文件类型在复制到 AWS S3 时发生变化
- android - 使用 adb 和活动管理器在 Android 上捕获具有指定名称的 JPEG 图像
- spring - 为每个端点设置 spring.security.oauth2.resourceserver.jwt.jwk-set-uri
- flutter - 是否可以在 Flutter 的函数中将类作为参数传递?
- laravel - 如何将多个关联数组条目发布到邮递员以及如何在 laravel 控制器中访问它
- java - Springboot JPA 将列连接为实体
- android - 异常的 WRAP_CONTENT 行为
- google-roads-api - Google Roads API“未找到请求的实体”
- regex - 使用额外参数和更改函数名称的批量重构函数调用
- c# - 如何使用 [HttpPut] 动词访问 WebApi 控制器中的 HttpParams