Search code examples
springosgiapache-servicemixfuse

access Spring context in OSGi bundle


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?


Solution

  • 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.

    Also see my comment below.