如何在不同的包中使用 OSGI 服务
how can I use OSGI service in different package
假设我有 Bundle A,它有一个接口 HelloWorld 和函数 helloWorld()
现在,在另一个 bundle 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();
您可以使用属性和过滤器来选择您想要获得的实现。
例如,您可以在捆绑包 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)")
假设我有 Bundle A,它有一个接口 HelloWorld 和函数 helloWorld()
现在,在另一个 bundle 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();
您可以使用属性和过滤器来选择您想要获得的实现。
例如,您可以在捆绑包 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)")