Spring:将ApplicationContext的对象注入ApplicationContext

时间:2011-03-29 19:52:05

标签: spring dependency-injection legacy-code

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

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

我想从 LegacyPlugin 启动ApplicationContext,并通过BeanFactory将其注入ApplicationContext,以创建其他对象。然后将重写代码,以使用setter injection&等等。

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

以下是我想要的代码:

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

 }

<!-- 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>

2 个答案:

答案 0 :(得分:4)

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

ApplicationContext ctx = new ClassPathXmlApplicationContext();
ctx.setConfigLocation("context.xml");

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

ctx.refresh();

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

答案 1 :(得分:0)

实际上,这不起作用......它会导致以下错误:

BeanFactory not initialized or already closed
call 'refresh' before accessing beans via the ApplicationContext

最终解决方案是使用GenericApplicationContext

GenericApplicationContext ctx = new GenericApplicationContext();
ctx.getBeanFactory().registerSingleton("plugin", this);
new XmlBeanDefinitionReader(ctx).loadBeanDefinitions(
    new ClassPathResource("context.xml"));
ctx.refresh();