【问题标题】:Is it best to use type or properties to choose between OSGi Declarative Services?最好使用类型或属性在 OSGi 声明式服务之间进行选择?
【发布时间】:2012-09-06 12:50:56
【问题描述】:

我目前正在将一段代码从纯 Java 代码转换为 OSGi 声明式服务。

原始纯 Java 代码

new AggregateServiceImpl(
    new ChildServiceImpl1(),
    new ChildServiceImpl2(),
    new ChildServiceImpl3()
);

类是这样声明的:

class AggregateServiceImpl implements Service
class ChildServiceImpl1 implements Service
class ChildServiceImpl2 implements Service
class ChildServiceImpl3 implements Service

所以所有类都实现了 Service,但是 Aggregate 实现能够在调用时推迟到子 Service。

AggregateServiceImpl 本身不知道其他实现的存在。它的构造函数最初声明为:

public class AggregateServiceImpl(Service... children)

澄清:接口名称“服务”是通用的,并不代表 OSGi DS 或服务概念。

转换为 OSGi

首先,我将每个实现移动到自己的包中。然后我声明我的组件(服务实现)。我碰巧在使用bnd,所以我使用服务注释。例如:

@Component
class ChildServiceImpl1 implements Service

在客户端类中,我们可以使用低级 OSGi API 查找服务或使用该捆绑包中的 DS 为我们创建对象。

问题

查找“服务”的最佳方式是什么?我想要 AggregateServiceImpl 但我可能会收到其中一个 ChildServiceImpl。

在查找 ServiceReferences 时,最好使用单独的服务类型或将属性添加到其中一个组件(例如“isRootService”)以用作过滤器?

【问题讨论】:

    标签: java osgi declarative-services


    【解决方案1】:

    最好的方法是使用服务注册属性

     @Component
     @Service
     @Property(name = "service.id", value = "<some service unique ID")
     class ChildServiceImpl1 implements Service{...}
    

    当你寻找一些特定的服务时,你可以使用服务过滤器:

    bc.getServiceReferences(Service.class.getName(), "(service.id=<some value>)");
    

    或者如果您想在 DS 组件中使用它作为服务参考:

    @Reference(target = "(service.id=<some value>)", cardinality = ...)
    private Service service;
    

    【讨论】:

    • 谢谢,这就是我目前正在做的事情。
    【解决方案2】:

    如果 AggregateServiceImpl 是唯一被其他捆绑包使用的 Service,那么它应该是您注册的唯一一个。

    根据您当前显示的代码,我们无法判断 AggregateServiceImpl 类是否依赖于 Service 或实际实现。

    如果它直接依赖于其他实现,而不是 Service 接口(正如您当前描述的那样),聚合包应该直接创建它需要的其他实现类,然后注册 AggregateServiceImpl 作为一个服务

    如果其他实现也需要在其他地方使用,那么您应该使用属性(如您所建议的那样),以便消费者可以区分它们。在这种情况下,你仍然不能使用 DS 来构建你的聚合,因为它不依赖于 Service

    【讨论】:

    • 不,它依赖于服务。它不关心其子代的实现细节,也不知道这些类的存在(尽管客户端代码当然在原始 Java 代码中是这样做的)。感谢您指出了这一点。其他实现作为服务来来去去。服务关系的基数为 0...n。
    猜你喜欢
    • 2023-03-25
    • 2015-04-12
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    • 2013-10-09
    相关资源
    最近更新 更多