如何从另一个上下文访问bean

3

我想要访问一个在不同上下文中自动连接的Spring bean。

这可能吗?

我认为我可以使用ApplicationContext并使用类似以下代码进行连接:

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationContextProvider implements ApplicationContextAware {
    private static ApplicationContext ctx = null;
    public static ApplicationContext getApplicationContext() {
        return ctx;
    }
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        this.ctx = ctx;
    }
}


<bean id="applicationContextProvider" class="ApplicationContextProvider"></bean>

这是否正确?

1个回答

1
不,你正在为声明bean的当前上下文创建一个监听器。

我想访问在另一个上下文中自动装配的Spring bean。

如果您需要进行一些自动装配,则需要使用<import>@Import导入其他上下文,具体取决于您的配置类型(java vs xml)。例如

<import resource="classpath:/path/to/otherAppContext.xml" />

如果您只想获取一个bean,您可以始终创建另一个ApplicationContext并使用getBean()方法。
ApplicationContext otherContext = ...// get other context  
BeanClass otherBean = otherContext.getBean(BeanClass.class);

您也可以像ContextLoaderListenerDispatcherServlet一样以相同的方式合并应用程序上下文。有关详细信息,请查看源代码。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接