java - 有没有办法找出哪些 bundle 正在使用我的 bundle ?

标签 java osgi

我正在构建一个 OSGI 框架,我想知道是否有办法获取所有绑定(bind)到我的 bundle?

这是因为我为这些 bundle 提供服务,并在提供此服务的同时创造新的资源来优化我的表现。我还提供了一种在不再需要时销毁这些资源的方法,但我想要一个故障保护,以便在捆绑解绑时不首先删除他使用的资源。

我可以为此使用我的 BundleContext 吗?

最佳答案

您似乎在问两个不同的问题。在第一段中,您询问的是与您绑定(bind)的 bundle ,我将其解释为导入您导出的包装的 bundle 。第二,你问的是你服务的消费者;这些是正交问题。

第一个问题,可以使用BundleWiring API:

BundleWiring myWiring = myBundle.adapt(BundleWiring.class);
List<BundleWire> exports = myWiring.getProvidedWires(PackageNamespace.PACKAGE_NAMESPACE);
for (BundleWire export : exports) {
    Bundle importer = export.getRequirerWiring().getBundle()
}

对于服务,您可以使用ServiceFactory 模式。通过将您的服务注册为 ServiceFactory 的实例而不是直接注册为服务接口(interface)的实例,您可以跟踪使用您的服务的包。这是使用此模式的服务实现的框架:

public class MyServiceFactory implements ServiceFactory<MyServiceImpl> {

    public MyServiceImpl getService(Bundle bundle, ServiceRegistration reg) {
         // create an instance of the service, customised for the consumer bundle
         return new MyServiceImpl(bundle);
    }

    public void ungetService(Bundle bundle, ServiceRegistration reg, MyServiceImpl svc) {
         // release the resources used by the service impl
         svc.releaseResources();
    }
}

更新:由于您正在使用 DS 实现您的服务,因此事情会更容易一些。 DS 为您管理实例的创建……唯一有点棘手的事情是确定哪个包是您的消费者:

@Component(servicefactory = true)
public class MyComponent {

    @Activate
    public void activate(ComponentContext context) {
        Bundle consumer = context.getUsingBundle();
        // ...
    }
}

在许多情况下,您甚至不需要获取 ComponentContext 和消费包。如果您要为每个消费者包分配资源,那么您可以将它们保存到组件的实例字段中,并记住在您的 deactivate 方法中清理它们。 DS 将为每个消费者包创建一个组件类的实例。

关于java - 有没有办法找出哪些 bundle 正在使用我的 bundle ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17854034/

相关文章:

java - EJB 规范和 Java 版本 - 向后兼容性

java - 使用微调器更改值

java - 图片加载路径

eclipse - 什么是 p2 存储库?

osgi - bundle 的部署顺序

java - 使用 SimpleDateFormat 解析时间字符串

java - JPA:持久化 Map<String,Entity>

java - 基于 Maven 依赖项以编程方式构建和启动包含的应用程序

osgi - OSGi NP-Complete 中的分辨率问题吗?

java - Maven bundle 插件生成带有错误或缺失版本的 list