Search code examples
javaosgicdiweldpax

CDI+OSGI: bundle packages scope


I use javase and solution osgi (felix)+cdi(weld)+paxcdi. I have two bundles A and B. Bundle B is a lib bundle.

In bundle A I have one class and one package.

package com.example.firstpackage;
import com.example.secondpackage.Class2;
public class Class1{
   @Inject
   private Class2 class2;
}

In bundle B I have two classes and two packages

package com.example.secondpackage;
import com.example.thirdpackage.Class3;
public class Class2{
   @Inject
   private Class3 class3;
}

and

package com.example.thirdpackage;
public class Class3{
   ....
}

I install and start both bundles.

The problem - pax (or weld) for injecting in classes of bundle A scans only those packages which are imported for classes IN bundle A. In my example - CDI for injecting in Class1 Class2 will scan com.example.secondpackage of bundle B. However, it will throw exception as Class2 needs Class3 but com.example.thirdpackage is not scanned for bundle A (as it's not imported!!!). com.example.thirdpackage is only scanned for bundle B but, as I understand every bundles for cdi has its own scope. How to fix it?


Solution

  • If you don't change your system design, all you can do is to export thirdpackage from B and to import it into A.

    To achieve better encapsulation, you could factor out a service interface IClass2 implemented by Class2, make this class an @OsgiServiceProvider and use

    @Inject @OsgiService
    private IClass2 class2;
    

    in Class1.