首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring :将启动ApplicationContext的对象注入ApplicationContext

Spring :将启动ApplicationContext的对象注入ApplicationContext
EN

Stack Overflow用户
提问于 2011-03-29 19:52:05
回答 2查看 2.4K关注 0票数 4

我想在遗留应用程序中使用Spring。

核心部分是一个类,我们称之为LegacyPlugin,它代表了应用程序中的一种可插拔部分。问题是这个类也是数据库连接器,用于创建许多其他对象,通常是通过构造函数注入.

我想从ApplicationContext中启动一个LegacyPlugin,并将它注入到ApplicationContext中,例如通过BeanFactory来创建其他对象。然后将重写代码,使用setter注入等等。

我想知道实现这一目标的最佳途径是什么。到目前为止,我有一个使用BeanFactory的工作版本,它使用ThreadLocal来保存当前执行的插件的静态引用,但对我来说似乎很难看……

下面是我想要结束的代码:

代码语言:javascript
复制
public class MyPlugin extends LegacyPlugin {

    public void execute() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext();
        // Do something here with this, but what ?
        ctx.setConfigLocation("context.xml");
        ctx.refresh();
    }

 }
代码语言:javascript
复制
<!-- This should return the object that launched the context -->
<bean id="plugin" class="my.package.LegacyPluginFactoryBean" />

<bean id="someBean" class="my.package.SomeClass">
    <constructor-arg><ref bean="plugin"/></constructor-arg>
</bean>

<bean id="someOtherBean" class="my.package.SomeOtherClass">
    <constructor-arg><ref bean="plugin"/></constructor-arg>
</bean>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-04-13 22:26:37

实际上这不管用..。它会导致以下错误:

代码语言:javascript
复制
BeanFactory not initialized or already closed
call 'refresh' before accessing beans via the ApplicationContext

最后的解决方案是使用GenericApplicationContext

代码语言:javascript
复制
GenericApplicationContext ctx = new GenericApplicationContext();
ctx.getBeanFactory().registerSingleton("plugin", this);
new XmlBeanDefinitionReader(ctx).loadBeanDefinitions(
    new ClassPathResource("context.xml"));
ctx.refresh();
票数 0
EN

Stack Overflow用户

发布于 2011-03-29 21:17:07

SingletonBeanRegistry接口允许您通过其registerSingleton方法手动将预配置的单例注入上下文,如下所示:

代码语言:javascript
复制
ApplicationContext ctx = new ClassPathXmlApplicationContext();
ctx.setConfigLocation("context.xml");

SingletonBeanRegistry beanRegistry = ctx.getBeanFactory();
beanRegistry.registerSingleton("plugin", this);

ctx.refresh();

这将将plugin bean添加到上下文中。您不需要在context.xml文件中声明它。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5478116

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档