【问题标题】:Is there a way to find out which bundles are using my Bundle?有没有办法找出哪些捆绑包正在使用我的捆绑包?
【发布时间】:2013-07-25 09:26:48
【问题描述】:

我正在构建一个 OSGI 框架,我想知道是否有办法让所有绑定到我的捆绑包?

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

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

【问题讨论】:

    标签: java osgi


    【解决方案1】:

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

    第一个问题,可以使用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 的实例而不是直接作为服务接口的实例,您可以跟踪使用您的服务的捆绑包。以下是使用此模式的服务实现框架:

    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 将为每个消费者捆绑包创建组件类的实例。

    【讨论】:

    • 我正在使用声明式服务,所以我不确定如何实现这一点,看到对于 servicefactory,我只是将其属性设置为“true”。当我使用 context.getService(ServiceReference sv) 时会自动调用我的 servicefactory 的 get 方法吗?
    猜你喜欢
    • 2021-08-08
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 2016-03-09
    • 2014-05-02
    • 1970-01-01
    相关资源
    最近更新 更多