0

我需要创建具有相同接口的服务组件。这意味着我对相同的接口有不同的实现。我试图创建两个具有相同界面的组件,其中一个仅处于活动状态。

我正在使用Equinox声明。你有更好的设计来解决这个问题吗?请在下面找到我的配置。

组件1.xml

 <?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="comp1">
   <implementation class="com.demo.impl.CompOneImpl"/>
   <service>
      <provide interface="com.demo.IComponent"/>
   </service>
 </scr:component>

组件2.xml

    <?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="comp2">
   <implementation class="com.demo.impl.CompTwoImpl"/>
   <service>
      <provide interface="com.demo.IComponent"/>
   </service>
 </scr:component>

从消费者访问组件

消费组件

comp1.xml

<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="consumeComp1">
   <implementation class="com.demo.service.ConsumeCompOne"/>
   <reference bind="setComp" cardinality="1..1" interface="com.demo.IComponent" name="comp1" policy="static" unbind="unsetComp"/>
</scr:component>

comp2.xml

<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="consumeComp2">
   <implementation class="com.demo.service.ConsumeCompTwo"/>
   <reference bind="setComp" cardinality="1..1" interface="com.demo.IComponent" name="comp2" policy="static" unbind="unsetComp"/>
</scr:component>

当我尝试通过 ConsumeCompOne 和 ConsumeCompTwo 类分别访问 comp1 和 comp2 时,我总是得到相同的组件,无论是 comp1 还是 comp2。请帮我解决这个问题。

先感谢您

牧牛姑娘

4

3 回答 3

1

您想使用元素target上的属性reference来选择要绑定的特定服务。

comp1.xml

<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="consumeComp1">
   <implementation class="com.demo.service.ConsumeCompOne"/>
   <reference bind="setComp" cardinality="1..1" interface="com.demo.IComponent" name="comp1" policy="static" unbind="unsetComp"
     target="(component.name=comp1)"/>
</scr:component>

comp2.xml

<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="consumeComp2">
   <implementation class="com.demo.service.ConsumeCompTwo"/>
   <reference bind="setComp" cardinality="1..1" interface="com.demo.IComponent" name="comp2" policy="static" unbind="unsetComp"
     target="(component.name=comp2)"/>
</scr:component>
于 2014-11-27T17:53:42.793 回答
1

DS 工作正常,所以这里没有什么需要解决的。

正如您所说,两个消费者组件都提供了一个IComponent服务实例,这正是它们作为引用请求的内容。

于 2014-11-27T10:03:14.107 回答
1

如果您希望能够选择服务的特定实例,请使用属性发布它以识别它。然后,在客户端上,您可以使用 OSGi 服务过滤器来选择匹配的服务过滤器,例如特殊的键/值组合。

于 2014-11-27T10:05:04.220 回答