Spring : Injecting the object that launches the ApplicationContext into the ApplicationContext

标签 spring dependency-injection legacy-code

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

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

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

我想知道实现这一目标的最佳方法是什么。到目前为止,我有一个使用 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>

最佳答案

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

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

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

ctx.refresh();

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

关于 Spring : Injecting the object that launches the ApplicationContext into the ApplicationContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5478116/

相关文章:

java - 在 Spring 中动态更改 Bean 引用

PHP 不正确的变量声明

c++ - 遗留 c++ 代码不包含 std::prefix

java - 当 bean 构造函数使用参数时 Spring init 失败

spring - "Request method ' POST ' not supported"放置安全注释后

java - 从 Hibernate 反序列化 JSON

database - 从旧数据结构到新数据结构的数据迁移

java - 以编程方式 hibernate `cache usage`参数

c# - ASP.NET WebAPI 中的依赖注入(inject) : IHttpControllerActivator vs. IDependencyResolver

c# - autofac 中的条件组件注册