jhamon
jhamon

Reputation: 3691

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.

Upvotes: 0

Views: 1326

Answers (2)

Christian Schneider
Christian Schneider

Reputation: 19606

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.

Upvotes: 1

Matt Pavlovich
Matt Pavlovich

Reputation: 4316

Sounds like you have a factory pattern and want to inject the created bean into the declared bean. Correct?

If so see: https://www.ibm.com/developerworks/library/os-osgiblueprint/

 <bean id=”accountFactory” class=“org.apache.geronimo.osgi.AccountFactory”>  
       <argument value=”account factory”/>      
   </bean>

   <bean id=”accountThree”
         factory-ref=“accountFactory” 
         factory-method=“createAccount”>   
       <argument value=”3”/>
       <property name=”description” value=”#3 account”/>      
   </bean>

Upvotes: 0

Related Questions