我想在遗留应用程序中使用Spring。
核心部分是一个类,我们称之为LegacyPlugin,它代表了应用程序中的一种可插拔部分。问题是这个类也是数据库连接器,用于创建许多其他对象,通常是通过构造函数注入.
我想从ApplicationContext中启动一个LegacyPlugin,并将它注入到ApplicationContext中,例如通过BeanFactory来创建其他对象。然后将重写代码,使用setter注入等等。
我想知道实现这一目标的最佳途径是什么。到目前为止,我有一个使用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>发布于 2011-04-13 22:26:37
实际上这不管用..。它会导致以下错误:
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();发布于 2011-03-29 21:17:07
SingletonBeanRegistry接口允许您通过其registerSingleton方法手动将预配置的单例注入上下文,如下所示:
ApplicationContext ctx = new ClassPathXmlApplicationContext();
ctx.setConfigLocation("context.xml");
SingletonBeanRegistry beanRegistry = ctx.getBeanFactory();
beanRegistry.registerSingleton("plugin", this);
ctx.refresh();这将将plugin bean添加到上下文中。您不需要在context.xml文件中声明它。
https://stackoverflow.com/questions/5478116
复制相似问题