在web.xml中配置监听器来控制ioc容器生命周期

、整合关键-在web.xml中配置监听器来控制ioc容器生命周期 原因:

1、配置的组件太多,需保障单实例

2、项目停止后,ioc容器也需要关掉,降低对内存资源的占用。 项目启动创建容器,项目停止销毁容器。

利用ServletContextListener监控项目来控制。 Spring提供了了这样的监控器:

在web.xml配置监听器:

复制代码

<!-- 监听项目的创建和销毁,依据此来创建和销毁ioc容器 -->
  <!-- needed for ContextLoaderListener -->
    <context-param>
        <!-- 指定Spring配置文件位置 -->
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!-- Bootstraps the root web application context before servlet initialization -->
    <!--项目启动按照配置文件指定的位置创建容器,项目卸载,销毁容器  -->
    <listener>
        <!-- 加载jar包:org.springframework.web -->
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

复制代码

打开

ContextLoaderListener源码发现其实现了ServletContextListener,其中有两个方法,一个创建容器,一个销毁容器

复制代码

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
//...
/**
     * Initialize the root web application context.
     */
    @Override
    public void contextInitialized(ServletContextEvent event) {
        initWebApplicationContext(event.getServletContext());
    }


    /**
     * Close the root web application context.
     */
    @Override
    public void contextDestroyed(ServletContextEvent event) {
        closeWebApplicationContext(event.getServletContext());
        ContextCleanupListener.cleanupAttributes(event.getServletContext());
    }

}

ContextLoader

初始化WebApplicationContext

由下面的核心代码可知,创建容器后得到一个context对象
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
//创建容器
if (this.context == null) {

 //private WebApplicationContext context;就是我们的ioc容器

this.context = createWebApplicationContext(servletContext);
            }
}

复制代码

context;就是我们的ioc容器,context有很多方法,

 由上图可知getCurrentWebApplicationContext()方法可以获取当前的ioc容器。

复制代码

    public static WebApplicationContext getCurrentWebApplicationContext() {
        ClassLoader ccl = Thread.currentThread().getContextClassLoader();
        if (ccl != null) {
            WebApplicationContext ccpt = currentContextPerThread.get(ccl);
            if (ccpt != null) {
                return ccpt;
            }
        }
        return currentContext;
    }

复制代码

getCurrentWebApplicationContext()属于ContextLoader类的,因为属于static,所以监听器来控制ioc容器生命周期
代码如下:
private static ApplicationContext ioc =  ContextLoader.getCurrentWebApplicationContext();

猜你喜欢

转载自blog.csdn.net/bingguang1993/article/details/83010089