Search code examples
javaosgicdiapache-felixweld

OSGi + Weld: FrameworkUtil getBundleContext() returns null


I use Apache Felix and weld and I have two classes:

@ApplicationScoped
class A {
  private B b= new B();
}

class B {
  private void foo(){
    BundleContext bc= FrameworkUtil.getBundle(this.getClass()).getBundleContext();
  }
}

Object is class A is created by CDI container and I think that's the reason that in class B FrameworkUtil.getBundle returns null. Maybe classloader problem or something like this. Of course I can get the reference to bundle context from A class as Weld injects it. But I don't want to keep this reference inside A and pass it to any other classes. Can I get the reference to bundle context inside B (without taking it from A)? I tried in B:

@Inject
BundleContext bundleContext;

But it didn't work. It can be important - these classes are in different bundles.


Solution

  • Probably the object instance has a type that the CDI container created at runtime by its own custom classloader (by creating a subclass of A).

    Instead of using calling

    BundleContext bc= FrameworkUtil.getBundle(this.getClass()).getBundleContext();
    

    try calling

    BundleContext bc= FrameworkUtil.getBundle(A.class).getBundleContext();
    

    In case type A is loaded by the ClassLoader of a bundle, this should work.

    Btw.: I recommend not to use Weld, CDI and other technologies within OSGi. They might be integrated, but they often cause lots of pain due to the tricks their tricks that work within Application Servers (where there is only one classloader / app).