有没有办法找出哪些捆绑使用我的Bundle?

时间:2013-07-25 09:26:48

标签: java osgi

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

这是因为我为这些捆绑提供服务,并在提供此服务的同时制作新资源以优化我的预备。我还提供了一种在不再需要的时候销毁这些资源的方法,但是我希望在没有首先删除他使用过的资源的情况下捆绑解除绑定时的故障保护。

我可以使用我的BundleContext吗?

1 个答案:

答案 0 :(得分:3)

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

对于第一个问题,您可以使用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和消费包。如果要为每个使用者分发包分配资源,则可以将它们保存到组件的实例字段中,并记住在停用方法中清除它们。 DS将为每个使用者包创建一个组件类的实例。