web应用是如何初始化Spring容器源码分析

    我们最常见的启动文件是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和依赖注入的入口类。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值