从头看看Tomcat启动Spring容器的原理

通过带注解Spring Boot可以启动一个web容器,并初始化bean容器。那么Tomcat启动并初始化spring容器的原理是怎样的?

Tomcat启动web程序时会创建一对父子容器(图1):

从头看看Tomcat启动Spring容器的原理

有几种方式:

  1. XML配置Spring和Servlet容器
  2. 通过注解初始化
  3. Servlet提供SPI的调用方式来启动

 

XML配置Spring和Servlet容器

web.xml主要通过一下配置初始化父子容器(父子容器是职责单一的设计)


<web-app>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> <!-- 初始化父容器-->
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/app-context.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>app</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 初始化子容器-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

Listener主要作用就是初始化spring的bean容器,servlet做request的转发


<listener> ==> @WebListerner
<Servlet> ==> @WebServlet
<Filter> ==> @WebFilter


Servlet提供SPI的调用方式来启动
从头看看Tomcat启动Spring容器的原理

 


 打开service文件有一行如下:

org.springframework.web.SpringServletContainerInitializer

就是给Tomcat提供初始化容器用的服务接口,Tomcat启动的时候就会通过ServiceLoader把这个类加载进来,然后调用该类的onStartUp方法来初始化
@HandlesTypes({WebApplicationInitializer.class})
public class SpringServletContainerInitializer implements ServletContainerInitializer {

 注解中的WebApplicationInitializer.clas就是引入的容器初始化类了。

看一下他的子类:

public abstract class SpringBootServletInitializer implements WebApplicationInitializer {
     public void onStartup(ServletContext servletContext) throws ServletException {
        this.logger = LogFactory.getLog(this.getClass());
        WebApplicationContext rootApplicationContext = this.createRootApplicationContext(servletContext);
        if (rootApplicationContext != null) {
            servletContext.addListener(new SpringBootServletInitializer.SpringBootContextLoaderListener(rootApplicationContext, servletContext));
        } else {
            this.logger.debug("No ContextLoaderListener registered, as createRootApplicationContext() did not return an application context");
        }

    }
}

其中的onStartup方法中有addListener,这个添加的Listener正是对应的XML中:<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

其中的SpringBootContextLoaderListener是该类的内部类,继承自ContextLoaderListener

其中的this.createRootApplicationContext(servletContext);便是创建图1中的父容器

 


上一篇:Servlet


下一篇:JavaWeb知识小汇(1)——ServletContext