web.xml加载spring的两种方式(servlet和listener)

摘自:http://elfasd.iteye.com/blog/1765939

在实际项目中spring的配置文件applicationcontext.xml是通过spring提供的加载机制,自动加载的容器中去,在web项目中,配置文件加载到web容器中进行解析,目前,spring提供了两种加载器,以供web容器的加载:一种是ContextLoaderListener,另一种是ContextLoaderServlet。这两种在功能上完全相同,只是一种是基于Servlet2.3版本中新引入的Listener接口实现,而另一种是基于Servlet接口实现,以下是这两种加载器在web.xml中的时机配置应用:

第一种:

<listener>
 <listener-class>org.springframework.context.ContextLoaderListener</listener-class>
</listener>

另一种:

<servlet>
 <servlet-name>context</servlet-name>
 <servlet-class>org.springframework.context.ContextLoaderServlet</servlet-class>
 <load-on-startup>1</load-on-startup>
</servlet>

通过上面的配置,web容器会自动加载applicationcontext.xml初始化。

如果需要指定配置文件的位置,可通过context-param加以指定:

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

之后,可以通过

WebApplicationContextUtils.getWebApplicationContext方法在web应用中获取applicationcontext的引用。

 

其实还有一种基于plugin的配置,但是推荐使用listener配置,servlet在3.0以后就不再使用了,一个基础的完整配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 

 <listener>
  <listener-class>
   org.springframework.web.context.ContextLoaderListener
  </listener-class>
 </listener>
 <!--contextConfigLocation在 ContextLoaderListener类中的默认值是 /WEB-INF/applicationContext.xml-->
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
  <!-- <param-value>classpath:applicationContext*.xml</param-value> -->
 </context-param>

 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

猜你喜欢

转载自jiejie234.iteye.com/blog/1880674