spring mvc 双亲上下文问题

来源:互联网 发布:淘宝隐形降权多久恢复 编辑:程序博客网 时间:2024/05/01 05:01

如果你使用了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,事情就简单了,什么麻烦事儿也没有了。