首页 文章

如何在不同的包中使用OSGI服务

提问于
浏览
3

假设我有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();

1 回答

  • 5

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

    例如,您可以在bundle 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)")
    

相关问题