How do I use a Spring bean inside an OSGi bundle?
Asked Answered
O

1

4

I have an application where I have to use Spring to load a bean based on some business conditions inside an OSGi bundle. This bean is not meant for export and is used for calculation inisde my bundle. Basically I have an actual service component, which is exported, and it has to use this Spring bean internally. But...

  1. When I use Spring DM the extender loads the application context in a seperate thread. How to access the context file inside my bundle?
  2. How to make sure extender thread finshes loading application context so that i can use it in my bundle?
  3. I don't want to export the application context as services as Spring DM does, as it's only used inside my bundle for internal purposes.

Is there any way to do this?

Organometallic answered 7/11, 2011 at 17:8 Comment(1)
Your question might get better attention if you add a language tag to it (i.e. Java). You also might want to clean up your spelling, grammar and capitalization; your question will be taken more seriously.Pen
M
11

You don't need Spring DM for what you are trying to accomplish.

It sounds like what you want to do is actually provide access to your context inside of your bundle and have some class do lookups via ctx.getBean(). If this is the case, just create the context in your bundle manually like you would if you were not in OSGi and make the calls. No Spring DM involved at all.

The one issue here is that you have to extend ClassPathXmlApplicationContext to provide the bundles classloader, as it will use the thread context classloader otherwise.

ApplicationContext ctx = new ClassPathXmlApplicationContext(myCtxPath)
{
    protected void initBeanDefinitionReader(XmlBeanDefinitionReader reader)
    {
        super.initBeanDefinitionReader(reader);
        reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
        reader.setBeanClassLoader(getClassLoader());
    }
}
Mycosis answered 9/11, 2011 at 15:44 Comment(2)
I had to add this to make it work: reader.setBeanClassLoader(properClassLoader);Maurilia
That is what the getClassLoader() method is for, as mentioned you have to supply the bundle classloader.Mycosis

© 2022 - 2024 — McMap. All rights reserved.