<转载>springmvc(31):Spring中的 ContextLoaderListener

本文详细解析了Spring框架中ContextLoaderListener的工作原理及其加载过程。它通过实现ServletContextListener接口,在Web容器启动时自动装配applicationContext.xml配置信息。文章还介绍了如何自定义配置文件的位置和名称。

2018年2月22日

------------------blog 1

Spring之ContextLoaderListener的作用

Spring org.springframework.web.context.ContextLoaderListener

public class ContextLoaderListener

extends Objectimplements ServletContextListener

作用:在启动Web容器时,自动装配Spring applicationContext.xml的配置信息。

因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。在ContextLoaderListener中关联了ContextLoader这个类,所以整个加载配置过程由ContextLoader来完成。

看看ContextLoader的API说明

 

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

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

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

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

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/classes/applicationContext-*.xml
</param-value>
</context-param>

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

-----------------------------------------------------------------------------------------

例子,在web.xml文件中加入下面代码

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

如果applicationContext.xml文件没有在/WEB-INF/下,或文件名不一致,或存在多个Spring配置文件,在web.xml文件中根据下面代码修改

  <context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath*:applicationContext-*.xml,/WEB-INF/applicationContext.xml,/WEB-INF/classes/applicationContext-*.xml
</param-value>

----------------------------blog 2--《ContextLoaderListener加载过程

以下描述,将是最详细版spring的ContextLoaderListener加载过程,没有之一。

ContextLoaderListener实现了ServletContextListener接口,ServletContextListener是Java EE标准接口之一,类似tomcat,jetty的java容器启动时便会触发该接口的contextInitialized。

1 顾,java容器启动触发ContextLoaderListener的contextInitialized

2 contextInitialized 方法调用ContextLoader的initWebApplicationContext方法。

3 initWebApplicationContext调用createWebApplicationContext方法

4 createWebApplicationContext 调用determineContextClass方法

5 determineContextClass有如下代码

contextClassName = defaultStrategies
                .getProperty(WebApplicationContext.class.getName());
 
  • 1
  • 2

显然是从defaultStrategies中加载的

ContextLoader 类中有段静态代码

static {
        try {
            ClassPathResource resource = new ClassPathResource(
                    "ContextLoader.properties", ContextLoader.class);
            defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
        } catch (IOException ex) {
            throw new IllegalStateException(
                    "Could not load 'ContextLoader.properties': "
                            + ex.getMessage());
        }

        currentContextPerThread = new ConcurrentHashMap(1);
    }
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

ContextLoader.properties 文件内容如下:

org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext

至此,determineContextClass方法返回的是XmlWebApplicationContext

6 回到 initWebApplicationContext 方法,调用configureAndRefreshWebApplicationContext方法

7 configureAndRefreshWebApplicationContext 调用了AbstractApplicationContext的refresh方法

8 refresh 方法调用了obtainFreshBeanFactory

9 obtainFreshBeanFactory 调用了AbstractRefreshableApplicationContext类的refreshBeanFactory方法

10 refreshBeanFactory调用了XmlWebApplicationContext的loadBeanDefinitions

11 loadBeanDefinitions中加载了对应的applicationContext.xml



<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>spring</display-name> <!-- 加载Spring配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring.xml</param-value> </context-param> <!-- 字符集 过滤器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Spring监听器 --> <listener> <description>Spring监听器</description> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 防止Spring内存溢出监听器 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- Spring MVC --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <description>SpringMVC</description> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 本次需要做的配置,注意位置,要放在配置springmvc的url-pattern之前 --> <!-- 表示当程序加载符合这些路径的资源时,不会通过dispatchservlet --> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> <url-pattern>*.css</url-pattern> <url-pattern>*.html</url-pattern> <url-pattern>/upload/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- Session超时时间 --> <!-- <session-config> <session-timeout>15</session-timeout> </session-config> --> </web-app>
06-14
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>ssm</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>ssm</name> <url>http://maven.apache.org</url> <properties> <maven.compiler.source>17</maven.compiler.source> <maven.compiler.target>17</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>6.2.6</spring.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>jakarta.servlet</groupId> <artifactId>jakarta.servlet-api</artifactId> <version>6.0.0</version> </dependency> <dependency> <groupId>jakarta.servlet.jsp.jstl</groupId> <artifactId>jakarta.servlet.jsp.jstl-api</artifactId> <version>3.0.2</version> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>8.4.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.25</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.18</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>3.0.4</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.3.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.19.0</version> </dependency> </dependencies> </project> public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[]{SpringConfig.class}; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{SpringMvcConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } } 为什么我的WebAppInitializer没加载上
06-21
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值