开发者

How can I get Symbolic-Name of an Osgi bundle which is using one of my exported packages?

开发者 https://www.devze.com 2022-12-26 07:33 出处:网络
Inside one of my implementation libraries I want to know from which user library request is coming from?

Inside one of my implementation libraries I want to know from which user library request is coming from?

Bundle A ClientCode -- > ServiceInterface

Bundle B ClientCode -- > ServiceIn开发者_开发问答terface

Bundle C ServiceInterface ServiceImpl.

And those interfaces are resolved by one of impl. bundles (Bundle C). Inside that bundle I want to know from which bundle request is coming from (A or B)?

Thanks.


You could add a parameter for the BundleContext to your interface methods. Then, when the client code calls into your service, passing in its bundle context, you can call context.getBundle().getSymbolicName() or other methods to get information about the bundle from which the call came.


The correct way to do this is to use a ServiceFactory, as explained in the OSGi specification. If you register your service as a service factory, you can supply an implementation for each "client" (where "client" is defined as bundle, invoking your service). This allows you to know who is invoking you, without the client having to specify anything as it's clearly not good design to add a parameter called BundleContext (unless there is no other way).

Some "pseudo" code:

class Bundle_C_Activator implements BundleActivator {
  public void start(BundleContext c) {
    c.registerService(ServiceInterface.class.getName(),
      new ServiceFactory() {
        Object getService(Bundle b, ServiceRegistration r) {
          return new ServiceImpl(b); // <- here you hold on to the invoking bundle
        }
        public void ungetService(Bundle b, ServiceRegistration r, Object s) {}
      }, null);
  }
}

class ServiceImpl implements ServiceInterface {
  ServiceImpl(Bundle b) {
    this.b = b; // <- so we know who is invoking us later
  }
  // proceed here with the implementation...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消