且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在OSGi包中使用Spring bean?

更新时间:2021-12-01 23:40:23

您不需要Spring DM来完成您想要完成的任务。

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

听起来你想要做的事实上是提供对你的bundle内部的上下文的访问,并让一些类通过ctx.getBean()进行查找。如果是这种情况,只需手动创建捆绑包中的上下文,就像您不在OSGi中进行调用一样。根本没有涉及Spring DM。

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.

这里的一个问题是你必须扩展ClassPathXmlApplicationContext以提供bundle类加载器,否则它将使用线程上下文类加载器。

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());
    }
}