我们最常见的启动文件是web.xml,配置了监听器 org.springframework.web.context.ContextLoaderListener,具体流程是如何的呢?
当Tomcat启动完成后,会回调org.springframework.web.context.ContextLoaderListener的contextInitialized方法,完成Spring容器的初始化。javax.servlet.ServletContextListener是Tomcat容器提供的回调监听,提供了2个方法contextInitialized和contextDestroyed,contextInitialized是Tomcat容器在启动完成后的回调,ContextLoaderListener实现了该方法,用来初始化Spring容器;contextDestroyed是Tomcat容器在销毁时的回调,ContextLoaderListener实现了该方法,用来销毁spring容器中的单例等资源。
这里我重写了ContextLoaderListener,用来测试Tomcat的启动过程。
public class MyContextLoaderListener extends ContextLoaderListener { @Override public void contextInitialized(ServletContextEvent event) { super.contextInitialized(event); System.out.println("MyContextLoaderListener contextInitialized"); } @Override public void contextDestroyed(ServletContextEvent event) { super.contextDestroyed(event); System.out.println("MyContextLoaderListener contextDestroyed"); } }
<listener> <listener-class>com.hand.service.com.hand.listener.MyContextLoaderListener</listener-class> </listener>
由于我们这次是web应用,所以初始化SPring容器是org.springframework.web.context.support.XmlWebApplicationContext,之前是通过org.springframework.context.support.ClassPathXmlApplicationContext和org.springframework.context.support.FileSystemXmlApplicationContext来初始化容器的。
可以看到默认初始化的策越是在ContextLoader.properties这个文件定义的,并且不能改。看下图
该方法就会去加载bean的配置文件和初始化Ioc容器了。
<context-param> <param-name>contextConfigLocation</param-name><!--这里是说明,本次测试没配置。-->
<param-value> classpath*:serviceA.xml </param-value> </context-param>
因为框架是按contextConfigLocation来取的,所以上面的name必须是contextConfigLocation。值可以是多个,用逗号分隔,也可以用*通配符。
加载完bean定义了,后面的实例化和依赖注入参考之前博文Spring中Xml配置Bean的依赖注入源码分析
总结:
1.ServletContextListener是Tomcat提供的监听类,当Tomcat启动完成,通知Spring容器实例化。
1.ContextLoaderListener是启动Spring容器的入口类,实现了Tomcat提供的监听类ServletContextListener。
2.XmlWebApplicationContext是加载bean定义,实例化bean和依赖注入的入口类。