spring学习札记(2)-ContextLoader篇-视图层加载sping的几种方式
spring学习笔记(2)-ContextLoader篇-视图层加载sping的几种方式
与BeanFactory通常以编程的方式被创建不同的是,ApplicationContext能以声明的方式创建,如使用ContextLoader。当然你也可以使用ApplicationContext的实现之一以编程的方式创建ApplicationContext实例。首先,让我们先分析ContextLoader接口及其实现。
ContextLoader接口有两个实现:ContextLoaderListener和ContextLoaderServlet。两者都实现同样的功能,但不同的是,ContextLoaderListener不能在与Servlet 2.2兼容的web容器中使用。根据Servlet 2.4规范, servlet context listener要在web应用程序的servlet context建立后立即执行,并要能够响应第一个请求(在servlet context要关闭时也一样):这样一个servlet context listener是初始化Spring ApplicationContext的理想场所。虽然使用哪个完全取决于你,但是在同等条件下应该首选ContextLoaderListener;对于更多兼容性的信息,请查看ContextLoaderServlet的JavaDoc。
你可以象下面那样使用ContextLoaderListener来注册一个ApplicationContext:
在第一篇笔记中提到了自动载入一个Spring ApplicationContext,如果有不了解的可以看看。
在这里顺便提下j2ee web程序加载spring环境的几种方法,除了上面讲到的ContextLoaderListener和ContextLoaderServlet,还有一种就是在struts中加载的,运用org.springframework.web.struts.ContextLoaderPlugIn。
看这个例子:
任选一种即可加载spring环境。
不过建议用ContextLoaderListener就可以了,否则稍微不注意就会出现OpenSessionInViewFilter的session关闭问题。
与BeanFactory通常以编程的方式被创建不同的是,ApplicationContext能以声明的方式创建,如使用ContextLoader。当然你也可以使用ApplicationContext的实现之一以编程的方式创建ApplicationContext实例。首先,让我们先分析ContextLoader接口及其实现。
ContextLoader接口有两个实现:ContextLoaderListener和ContextLoaderServlet。两者都实现同样的功能,但不同的是,ContextLoaderListener不能在与Servlet 2.2兼容的web容器中使用。根据Servlet 2.4规范, servlet context listener要在web应用程序的servlet context建立后立即执行,并要能够响应第一个请求(在servlet context要关闭时也一样):这样一个servlet context listener是初始化Spring ApplicationContext的理想场所。虽然使用哪个完全取决于你,但是在同等条件下应该首选ContextLoaderListener;对于更多兼容性的信息,请查看ContextLoaderServlet的JavaDoc。
你可以象下面那样使用ContextLoaderListener来注册一个ApplicationContext:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- or use the ContextLoaderServlet instead of the above listener <servlet> <servlet-name>context</servlet-name> <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> --> 监听器首先检查contextConfigLocation参数,如果它不存在,它将使用/WEB-INF/applicationContext.xml作为默认值。如果已存在,它将使用分隔符(逗号、冒号或空格)将字符串分解成应用上下文将位置路径。ContextLoaderServlet同ContextLoaderListener一样使用'contextConfigLocation'参数。
在第一篇笔记中提到了自动载入一个Spring ApplicationContext,如果有不了解的可以看看。
在这里顺便提下j2ee web程序加载spring环境的几种方法,除了上面讲到的ContextLoaderListener和ContextLoaderServlet,还有一种就是在struts中加载的,运用org.springframework.web.struts.ContextLoaderPlugIn。
看这个例子:
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> <set-property property="contextConfigLocation" value="/WEB-INF/applicationContext.xml,/WEB-INF/action-servlet.xml" /> </plug-in>
任选一种即可加载spring环境。
不过建议用ContextLoaderListener就可以了,否则稍微不注意就会出现OpenSessionInViewFilter的session关闭问题。