【问题标题】:how can I use OSGI service in different package如何在不同的包中使用 OSGI 服务
【发布时间】:2016-06-26 19:43:29
【问题描述】:

假设我有 Bundle A,它有一个接口 HelloWorld 和函数 helloWorld()

现在,在另一个捆绑包 B 中,我的实现如下

@Service(HelloWorld.class)
@Component(immediate = true)
public class Test1Impl implements HelloWorld
{
  public String helloWorld()
  {
    return "I'm from Bundle B";
  }
}

我还有一个捆绑包 C,我正在做

@Service(HelloWorld.class)
@Component(immediate = true)
public class Test2Impl implements HelloWorld
{
  public String helloWorld()
  {
    return "I'm from Bundle C";
  }
}

现在,如果我只需要实现 Bundle C,我该怎么办? 例如,通常我会按照以下方式进行操作,但在这种情况下它不起作用。

Helloworld obj = sling.getService(HelloWorld.class);
obj.helloWorld();

【问题讨论】:

  • “它不起作用”是什么意思?这没有提供任何信息。请说明您预期会发生什么,以及实际发生了什么。
  • @NeilBartlett,我的意思是我没有得到想要的结果“我来自 Bundle C”,而是得到“我来自 Bundle B”,我猜这是因为 Bundle B 已解决首先。
  • 不,这与谁先解决无关。您可以获得其中任何一个实现,因为它们对于您请求的服务接口都是同样有效的匹配项。

标签: osgi aem sling


【解决方案1】:

您可以使用属性和过滤器来选择要获取的实现。

例如,您可以在包 C 中的实现上放置一个属性:

@Service(HelloWorld.class)
@Component(immediate = true)
@Property(name = "bundle", value = "bundle-c")
public class Test2Impl implements HelloWorld { .. }

然后使用过滤器来获取此实现。您将获得与过滤器匹配的一系列服务。

HelloWorld[] services = sling.getServices(HelloWorld.class, "(bundle=bundle-c)")

默认情况下,DS 会放置一个带有组件名称的属性。该属性为“component.id”,组件的名称默认为实现的完整类名。所以你也可以使用:

HelloWorld[] services = sling.getServices(HelloWorld.class, "(component.id=package.Test2Impl)")

【讨论】:

  • 如果我想通过@Reference 访问然后reference.target 是正确的方式?
  • 是的,“目标”是一个osgi过滤器,和getServices一样
猜你喜欢
  • 2013-06-14
  • 2013-10-18
  • 2013-08-26
  • 2010-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-12
相关资源
最近更新 更多