Search code examples
javadependency-injectionosgiblueprint-osgi

OSGI - Inject bean in new object


I may not fully grasp the concept of beans and services but all my researches lead me to nothing.

In my OSGI project, I got a bundle A that provide a service (called myService).

A bundle B consume this service in a bean (called myBean) that is also exposed as a service.

Beans and service declaration is done in Blueprint.

For now, both bundle A and B are resolved by Karaf and the wiring is ok.

But my bundle B has another bean (called myOtherBean), also exposed as service, that dynamically creates new objects. Those objects (called MyObject) must have a reference on the bean myBean.

How could I pass the reference?

An easy way would be to put the reference in my bean myOtherBean and inject it through the constructor of MyObject. But I am wondering if there could be another way to do that. Some suggested to use the @Inject annotation in MyObject but I can't make it work.


Solution

  • I think passing the service in the constructor is a good way to do this. Using a factory is possible but if you want to create the object in code it is difficult to use a blueprint factory. You can do it by injecting the blueprint context and retrieving the object from it manually but this is pretty ugly.