Search code examples
javaspringosgiapache-karafapache-servicemix

OSGi bundle access Spring context file from another bundle


I have an existing application that exists as multiple Spring projects. Project A's Spring context XML file improts B's Spring context XML file using

<import resource="classpath*:/META-INF/spring/BContext.xml" />

However, it I get a FileNotFoundException. I assume this is caused by the fact that the resource is not exposed by project B's bundle. I can access the classes, but not the file.

When researching this issue the common comment was to use OSGi services and inject the services instead of trying to inject the beans directly. However, since this is an existing application, I would like to avoid rewiring the entire thing.

Is there any way to tell OSGi to export the resource? I'm running ServiceMix on Karaf.


Solution

  • It's just a classpath resource, so I would assume adding an appropriate Export-Package directive would do the trick. That's definitely not the right way to do it, though. The path of that context file suggests that perhaps the project that contains BContext.xml is already set up to work with Spring Dynamic Modules. If so, then when you start that bundle, the Spring ApplicationContext is exported as a service. Look for it in your OSGi console.

    Edit: In response to discussion in the comments:

    I've never tried this myself, but theoretically it should be possible to use Spring DM's osgi namespace to make a bean reference to the OSGi service which is project B's ApplicationContext. Then, having a bean which is the ApplicationContext, you can use normal Spring configuration to extract beans from it using one of the getBean() methods. Note that you can use <constructor-arg ... /> to specify arguments to a factory method in a Spring config, as shown toward the bottom of this examples section.