Spring深度解析-16、Web环境下的IOC容器上下文初始化概述

如何在web.xml中配置,使tomcat容器加载时能初始化Spring的IOC容器?

可以通过ContextLoaderListener监听器的配置,实现在tomcat容器加载时初始化Spring的IOC容器。

ContextLoaderListener

这个监听器的源代码如下,他继承自ContextLoader,实现了ServletContextListener接口,一个典型的适配器模式。ServletContextListener会监听web容器的生命周期,当容器启动时,会调用监听器的contextInitialized,当容器销毁时就会调用contextDestroyed,因此可以在监听器的这两个方法内,做一些操作。
ContextLoaderListener用于监听tomcat容器,启动时调用contextInitialized来初始化Web环境的IOC容器的上下文,在tomcat关闭时做IOC容器的销毁操作。
具体的细节,不在这里说,明天详细讲解。

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
    private ContextLoader contextLoader;

    public ContextLoaderListener() {
    }

    public ContextLoaderListener(WebApplicationContext context) {
        super(context);
    }

    public void contextInitialized(ServletContextEvent event) {
        this.contextLoader = this.createContextLoader();
        if (this.contextLoader == null) {
            this.contextLoader = this;
        }

        this.contextLoader.initWebApplicationContext(event.getServletContext());
    }

    /** @deprecated */
    @Deprecated
    protected ContextLoader createContextLoader() {
        return null;
    }

    /** @deprecated */
    @Deprecated
    public ContextLoader getContextLoader() {
        return this.contextLoader;
    }

    public void contextDestroyed(ServletContextEvent event) {
        if (this.contextLoader != null) {
            this.contextLoader.closeWebApplicationContext(event.getServletContext());
        }

        ContextCleanupListener.cleanupAttributes(event.getServletContext());
    }
}

ServletContextListener

ServletContextListener是一个事件监听器,用来监听ServletContextEvent这个事件,这个事件在容器启动和销毁时触发。

ServletContext是什么?

在ContextLoaderListener的contextInitialized中可以看到,在触发事件时,监听器可以直接得到事件对象,通过事件对象中的getServletContext方法取得的ServletContext对象来参与容器上下文的初始化。
那么getServletContext取得的ServletContext是什么呢?
简单来说:
他就是一个工程的全局对象,称之为Servlet上下文,他是工程中全局唯一共享的对象。工程内所有的Servlet都共享这个上下文对象。
可以使用他来获取全局配置参数、资源文件等,他可以持有各个servlet的上下文对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值