如果你使用了listener監聽器來加載配置,一般在Struts+Spring+Hibernate的項目中都是使用listener監聽器的。如下
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Spring會創建一個全局的WebApplicationContext上下文,稱爲根上下文 ,保存在 ServletContext中,
key是WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE屬性的值。
可以使用工具類取出上下文:WebApplicationContextUtils.getWebApplicationContext(ServletContext);
DispatcherServlet是一個Servlet,可以同時配置多個,每個 DispatcherServlet有一個自己的 WebApplicationContext上下文,這個上下文繼承了 根上下文 中所有東西,保存在 ServletContext中,
key是"org.springframework.web.servlet.FrameworkServlet.CONTEXT"+Servlet名稱。
當一個Request對象產生時,會把這個WebApplicationContext上下文保存在Request對象中,
key是DispatcherServlet.class.getName() + ".CONTEXT"。
可以使用工具類取出上下文:RequestContextUtils.getWebApplicationContext(request);
Spring中的 ApplicationContext實例可以被限制在不同的作用域(scope)中。
在web MVC框架中,每個 DispatcherServlet有它自己的WebApplicationContext ,這個context繼承了根WebApplicationContext 的所有bean定義。
這些繼承的bean也可以在每個serlvet自己的所屬的域中被覆蓋(override),覆蓋後的bean 可以被設置上只有這個servlet實例自己使用的屬性。
總結:不使用listener監聽器來加載spring的配置,改用DispatcherServlet來加載spring的配置,不要雙親上下文,只使用一個DispatcherServlet,事情就簡單了,什麼麻煩事兒也沒有了。