SSH答疑解惑系列(一)——spring容器是如何启动的

SSH框架十分受欢迎,其中有一个原因就是spring可以和Struts2框架无缝整合。在使用spring时,无需手动创建web容器,而是通过配置文件声明式创建spring容器。

在web应用中,创建spring容器有两种方式:

  1. 在web.xml中配置
  2. 利用第三方MVC框架创建

第一种比较常用,第二种方法只对特定框架有效,在此就不做介绍,下面只介绍第一种方法。

为了让Spring容器随Tomcat/JBoss等启动而自动启动,我们用到了ServletContextListener监听器来完成。

先来看下在项目的web.xml中,整合spring的配置。

<!-- 整合spring -->
  <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext.xml</param-value>
    </context-param>

上述配置中,
1、在ContextLoaderListener中,ContextLoaderListener监听器实现了ServletContextListener接口。他在创建时自动查找WEB/INF下的applicationContext.xml文件。

2、当需要导入的配置文件有多个时需要使context-param标签,来确定配置文件的文件名称。通过查找contextConfigLocation的初始化参数。

public void contextInitialized(ServletContextEvent event) {
    //1、加载spring的web容器
        this.contextLoader = createContextLoader();
    //2、初始化spring的web容器并加载配置文件。
        this.contextLoader.initWebApplicationContext(event.getServletContext());
    }

创建spring容器的大致流程:
    /**
     * 创建 ContextLoader. Can be overridden in subclasses.
     * @return the new ContextLoader
     */
    protected ContextLoader createContextLoader() {
        return new ContextLoader();
    }

这里写图片描述

小结:
ssh框架中,我们通过配置就可以实现spring容器随着Tomcat/Jboss等的启动而自动启动,而无需我们手动开启。这是通过监听器来实现的,当spring容器启动后,自动读取并加载相应的配置文件。

原文地址:https://www.cnblogs.com/saixing/p/6730245.html