0

我们有一个 Web 应用程序,其中包含一个根应用程序上下文 ( applicationContext.xml) 和一个调度程序 servlet ( dispatcher-servlet.xml),在我们的web.xml类似中定义:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

...

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

由于访问限制,我们显然无法DispatcherServlet从根父上下文访问任何 bean。

但是,我们希望能够访问兄弟bean。例如,在我们的dispatcher-servlet.xml我们有:

<bean id="firstController" class="org.springframework.web.servlet.mvc.multiaction.MultiActionController">
    ...
</bean>

<bean id="secondController" class="org.springframework.web.servlet.mvc.multiaction.MultiActionController">
...
</bean>

我们如何secondController从内部访问,firstController而不需要将其作为构造函数参数传入或设置为属性?

我们WebApplicationContextUtils.getWebApplicationContext(...)用来访问 root 中的兄弟姐妹applicationContext.xml,但我们想在子上下文中做同样的事情。(来自其中一个孩子。)

4

1 回答 1

0

您可以ApplicationContext使用

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("dispatcher-servlet.xml")

这是假设dispatcher-servlet.xml在类路径中。上下文对象必须被缓存。然后用于context.getBean()从任何地方访问 bean。

其他选项似乎是,使用重载方法,我们可以传递上下文属性名称。我没用过。 WebApplicationContextUtils.getWebApplicationContext(ServletContext sc, String attrName)

于 2012-12-14T16:11:17.557 回答