views:

46

answers:

1

I have an OSGi bundle that uses the bundle-context.xml file to initialize a bean.

<bean id="myBean" class="test.MyClass">
    <property name="output" value="test"/>
</bean>

I have a factory class that needs to get the bean instance. In the non-OSGI world, I've always just the following to initialize the context and get a handle to a bean...

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bundle-context.xml");
MyClass bean = (MyClass) applicationContext.getBean("myBean");

But, in OSGI (FuseESB 4.2, Servicemix4), the container automatically loads the bundle-context.xml file and initializes the spring context. If I load the context explicitly (using code above), then 2 contexts are created (which is bad). So, what is the proper way to get a handle to same context/bean?

+1  A: 

I suppose it is Spring Dynamic Modules which loads your context - so you should not do this for your own. Have a look at the Spring DM documentation - this will be useful.

Spring DM will publish the application context as an OSGi service. Have a look at the explanation here and follow the recommendations.

K. Claszen
thx, I have read this documentation...I still don't see an easy way to do this. Perhaps jumping through some OSGI registry hoops to get a handle to the context, but this should be a standard thing to do with Spring in OSGi. Am I missing something? I just want an instance of a bean defined in Spring?
BenODay
I just found that there is an Spring-Core ApplicationContextAware Interface that you can implement. The Context will than be injected to your implementation class. That should work and be a simpler solution. You can find examples on the web, e.g. http://howto-notes.blogspot.com/2009/03/spring-applicationcontextaware.html
K. Claszen