现在的位置: 首页 > 综合 > 正文

从一个web应用创建ApplicationContext

2012年02月17日 ⁄ 综合 ⁄ 共 1214字 ⁄ 字号 评论关闭

从一个web应用创建ApplicationContext

与BeanFactory总是以编程的方式创建相反,ApplicationContext可以通过使用比如ContextLoader声明式地被创建。当然你也可以用ApplicationContext的任一种实现来以编程的方式创建它。首先,我们来看看ContextLoader以及它的实现。

ContextLoader有两个实现:ContextLoaderListenerContextLoaderServlet。它们两个有着同样的功能,除了listener不能在Servlet 2.2兼容的容器中使用。自从Servelt 2.4规范,listener被要求在web应用启动后初始化。很多2.3兼容的容器已经实现了这个特性。使用哪一个取决于你自己,但是如果所有的条件都一样,你大概会更喜欢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 LISTENER<servlet>    <servlet-name>context</servlet-name>    <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>    <load-on-startup>1</load-on-startup></servlet>-->

这个listener需要检查contextConfigLocation参数。如果不存在的话,它将默认使用/WEB-INF/applicationContext.xml。如果它存在,它就会用预先定义的分隔符(逗号,分号和空格)分开分割字符串,并将这些值作为应用上下文将要搜索的位置。ContextLoaderServlet可以用来替换ContextLoaderListener。这个servlet像listener那样使用contextConfigLocation参数。

抱歉!评论已关闭.