Spring之ContextLoaderListener

来源:互联网 发布:网络女主播yy 编辑:程序博客网 时间:2024/06/05 09:26

作用:在启动Web容器时,自动装配Spring的applicationContext.xml的配置信息【Spring默认配置文件信息】,即负责初始化IOC容器。

默认位置:

If not explicitly specified, the context implementation is supposed to use adefault location (with XmlWebApplicationContext: "/WEB-INF/applicationContext.xml")


因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法【public void contextInitialized ( ServletContextEvent sce );方法,即在ServletContextListener接口中声明的方法】。

<!-- spring监听器 --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>

如果applicationContext.xml文件没有在/WEB-INF/下,或文件名不一致,或存在多个Spring配置文件,则必须在web.xml文件中添加自定义配置:

<!-- Spring配置文件位置 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath*:spring/spring*.xml</param-value></context-param>

同时,ContextLoaderListener继承了ContextLoader这个类,所以整个加载配置过程由ContextLoader来完成。


类的继承和实现关系如下:

Object  - java.lang    ContextLoader - org.springframework.web.context          ContextLoaderListener  - org.springframework.web.context-----------------------------------------------------------------ServletContextListener - javax.servlet    ContextLoaderListener  - org.springframework.web.context     

ContextLoader的API说明

 

第一段说明ContextLoader可以由ContextLoaderListener和ContextLoaderServlet生成。如果查看ContextLoaderServlet的API,可以看到它也关联了ContextLoader这个类而且它继承了HttpServlet类

 

第二段,ContextLoader创建的是XmlWebApplicationContext这样一个类,它实现的接口是WebApplicationContext->ConfigurableWebApplicationContext->ApplicationContext->

 

BeanFactory这样一来spring中的所有bean都由这个类来创建

 

第三段,讲如何部署applicationContext的xml文件,如果在web.xml中不写任何参数配置信息,默认的路径是"/WEB-INF/applicationContext.xml,在WEB-INF目录下创建的xml文件的名称必须是applicationContext.xml。如果是要自定义文件名可以在web.xml里加入contextConfigLocation这个context参数:

<!-- Spring配置文件位置 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath*:spring/spring*.xml</param-value></context-param>

注:在<param-value></param-value>里指定相应的xml文件名,如果有多个xml文件,可以写在一起并以“,”号分隔。上面的applicationContext-*.xml采用通配符,比如这那个目录下有applicationContext-ibatis-base.xml,applicationContext-action.xml,applicationContext-ibatis-dao.xml等文件,都会一同被载入。



阅读全文
0 0