面试官:说一下Spring MVC的启动流程呗

简介: 基于XML配置的容器启动过程我们常用的Spring MVC是基于Servlet规范实现的,所以我们先来回顾一下Servlet相关的内容。

基于XML配置的容器启动过程

我们常用的Spring MVC是基于Servlet规范实现的,所以我们先来回顾一下Servlet相关的内容。

网络异常,图片无法展示
|

如果我们直接用Servlet来开发web应用,只需要继承HttpServlet,实现service方法即可,HttpServlet继承自Servlet,Servlet中常用的方法如下

public interface Servlet {
    // 初始化,只会被调用一次,在service方法调用之前完成
    void init(ServletConfig config) throws ServletException;
    ServletConfig getServletConfig();
    // 处理请求
    void service(ServletRequest req, ServletResponse res)throws ServletException, IOException;
    String getServletInfo();
    // 销毁
    void destroy();
}

每个Servlet有一个ServletConfig,用来保存和Servlet相关的配置每个Web应用有一个ServletContext,用来保存和容器相关的配置

考虑到很多小伙伴可能对Servlet的很多用法不熟悉了,简单介绍一下,就用xml配置了,当然你可以用JavaConfig的方式改一下

项目结构如下

网络异常,图片无法展示
|

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
          http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
  <context-param>
    <param-name>configLocation</param-name>
    <param-value>test</param-value>
  </context-param>
  <servlet>
    <servlet-name>userServlet</servlet-name>
    <servlet-class>com.javashitang.controller.UserServlet</servlet-class>
    <init-param>
      <param-name>helloWord</param-name>
      <param-value>hello sir</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>userServlet</servlet-name>
    <url-pattern>/user.do</url-pattern>
  </servlet-mapping>
  <listener>
    <listener-class>com.javashitang.listener.MyServletContextListener</listener-class>
  </listener>
</web-app>
public class UserServlet extends HttpServlet {
    private String helloWord;
    @Override
    public void init(ServletConfig config) throws ServletException {
        this.helloWord = config.getInitParameter("helloWord");
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();
        String userId = req.getParameter("userId");
        out.println(helloWord + " " + userId);
    }
}

xml配置文件中可以用init-param标签给Servlet设置一些配置,然后在init方法中通过ServletConfig来获取这些配置,做初始化

访问
http://localhost:8080/user.do?userId=1
返回
hello sir 1

可以看到我们针对这个servlet还配置了load-on-startup这个标签,那么这个标签有什么用呢?

load-on-startup表示当容器启动时就初始化这个Servlet,数组越小,启动优先级越啊高。当不配置这个标签的时候则在第一次请求到达的时候才会初始化这个Servlet

context-param标签是容器的初始化配置,可以调用容器的getInitParameter方法获取属性值

Listener是一种扩展机制,当Web应用启动或者停止时会发送各种事件,我们可以用Listener来监听这些事件,做一些初始化工作。如监听启动事件,来初始化数据库连接等。

我这个demo只是获取了一下配置文件的位置,并打印出来。

public class MyServletContextListener implements ServletContextListener {
    // 容器启动
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext sc = sce.getServletContext();
        String location = sc.getInitParameter("configLocation");
        System.out.println(location);
    }
    // 容器销毁
    public void contextDestroyed(ServletContextEvent sce) {
    }
}

基于Xml写一个Spring MVC应用

我们基于xml方式写一个spring mvc应用,基于这个应用来分析,项目结构如下

网络异常,图片无法展示
|

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
          http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     version="3.1">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-context.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

spring-context.xml(配置service,dao层)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  <context:component-scan base-package="com.javashitang.service"/>
</beans>

spring-mvc.xml(配置和spring mvc相关的配置)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
     xmlns:mvc="http://www.springframework.org/schema/mvc"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
  <context:component-scan base-package="com.javashitang.controller"/>
  <mvc:annotation-driven/>
</beans>
@RestController
public class UserController implements ApplicationContextAware {
  @Resource
  private UserService userService;
  private ApplicationContext context;
  @RequestMapping("user")
  public String index(@RequestParam("userId") String userId) {
    return userService.getUsername(userId);
  }
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.context = applicationContext;
    System.out.println("UserController " + context.getId());
  }
}
public interface UserService {
  String getUsername(String userId);
}
@Service
public class UserServiceImpl implements UserService, ApplicationContextAware {
  private ApplicationContext context;
  @Override
  public String getUsername(String userId) {
    return userId;
  }
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.context = applicationContext;
    System.out.println("UserServiceImpl " + context.getId());
  }
}

我们之所以要用2个配置文件,是因为在Spring MVC中有2个容器

父容器由ContextLoaderListener来初始化,一般用来存放一些dao层和service层的Bean

子容器由DispatcherServlet来初始化,一般用来存放controller层的Bean

项目启动后从打印出的值就可以看出来,Service和Controller是从2个容器获取的

UserServiceImpl org.springframework.web.context.WebApplicationContext:
UserController org.springframework.web.context.WebApplicationContext:/dispatcher

子容器可以访问父容器中的Bean,父容器不能访问子容器中的Bean。当从子容器找不到对应的Bean时,会从父容器中找

父容器启动

父容器由ContextLoaderListener来初始化,当tomcat启动的时候,发布启动事件,调用ContextLoaderListener#contextInitialized方法,接着调用initWebApplicationContext方法

网络异常,图片无法展示
|

子容器启动

子容器的启动在DispatcherServlet#init方法中

DispatcherServlet中并没有重写init方法,那就实在父类中了,HttpServletBean重写了init方法

网络异常,图片无法展示
|

用流程图总结一下过程

网络异常,图片无法展示
|

如果你觉得父容器没啥作用的话,可以把所有的Bean都放在子容器中

当配置父子容器的时候还是比较容易踩坑的,比如在子容器中配置了Bean A,在父容器中配置了Bean B,Bean B使用自动注入依赖了Bean A,此时因为父容器无法查找子容器的Bean,就会抛出找不到Bean A的异常。

可能觉得父子容器这种设计并不是特别好,所以在Spirng MVC用JavaConfig的方式配置时或者用Spirng Boot开发时,都只存在单一的ApplicationContext

基于JavaConfig配置的容器启动过程

Servlet3.0以后出了新规范,Servlet容器容器在启动的时候需要回掉
javax.servlet.ServletContainerInitializer接口的onStartup方法,方法的实现类放在META-IN/services/javax.servlet.ServletContainerInitializer文件中,典型的spi代码

这个接口特别重要,Spring Boot中不用web.xml也能启动注册DispatcherServlet的奥秘就在这个接口上

网络异常,图片无法展示
|

Servlet3.0并且还提供了一个@HandlesTypes注解,里面指定一个类型,servlet容器会把该类型的子类或者实现类,放到
ServletContainerInitializer#onStartup方法中的webAppInitializerClasses参数中,然后实现自己的逻辑

网络异常,图片无法展示
|

基于JavaConfig写一个Spring MVC应用

用JavaConfig写一个Spring MVC应用超级简单

public class MyWebApplicationInitializer implements WebApplicationInitializer {
  @Override
  public void onStartup(ServletContext servletContext) throws ServletException {
    // Load Spring web application configuration
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.register(AppConfig.class);
    // Create and register the DispatcherServlet
    DispatcherServlet servlet = new DispatcherServlet(context);
    ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
    registration.setLoadOnStartup(1);
    registration.addMapping("/*");
  }
}
@EnableWebMvc
@ComponentScan("com.javashitang")
public class AppConfig {
}
@RestController
public class UserController {
  @RequestMapping("user")
  public String index(@RequestParam("userId") String userId) {
    return "hello " + userId;
  }
}

启动流程如下

  1. tomcat启动过程中回调ServletContainerInitializer#onStartup方法,并把@HandlesTypes中的WebApplicationInitializer实现类作为参数传入
  2. ServletContainerInitializer#onStartup方法会调用WebApplicationInitializer#onStartup,完成容器的初始化工作(我们只设置了一个容器哈)

启动过程除了Spring容器初始化是在Web容器回掉WebApplicationInitializer接口时发生的,其余的都一样

相关文章
|
1月前
|
安全 Java 数据库
一天十道Java面试题----第四天(线程池复用的原理------>spring事务的实现方式原理以及隔离级别)
这篇文章是关于Java面试题的笔记,涵盖了线程池复用原理、Spring框架基础、AOP和IOC概念、Bean生命周期和作用域、单例Bean的线程安全性、Spring中使用的设计模式、以及Spring事务的实现方式和隔离级别等知识点。
|
1月前
|
缓存 前端开发 中间件
[go 面试] 前端请求到后端API的中间件流程解析
[go 面试] 前端请求到后端API的中间件流程解析
|
5天前
|
缓存 安全 Java
Spring框架中Bean是如何加载的?从底层源码入手,详细解读Bean的创建流程
从底层源码入手,通过代码示例,追踪AnnotationConfigApplicationContext加载配置类、启动Spring容器的整个流程,并对IOC、BeanDefinition、PostProcesser等相关概念进行解释
Spring框架中Bean是如何加载的?从底层源码入手,详细解读Bean的创建流程
|
7天前
|
运维 测试技术
拆分软件测试流程,一张图秒杀所有面试
本文主要介绍了软件测试流程的核心内容,包括需求分析、测试用例编写、测试执行、缺陷提交及回归测试等关键步骤。以迭代测试为例,详细说明了每个环节的具体操作和注意事项,并提供了一张测试流程图以便理解。测试流程确保了软件质量,是面试中常见的考察点。
24 7
拆分软件测试流程,一张图秒杀所有面试
|
5天前
|
缓存 前端开发 Java
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
Soring Boot的起步依赖、启动流程、自动装配、常用的注解、Spring MVC的执行流程、对MVC的理解、RestFull风格、为什么service层要写接口、MyBatis的缓存机制、$和#有什么区别、resultType和resultMap区别、cookie和session的区别是什么?session的工作原理
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
|
5天前
|
缓存 Java 数据库
【Java面试题汇总】Spring篇(2023版)
IoC、DI、aop、事务、为什么不建议@Transactional、事务传播级别、@Autowired和@Resource注解的区别、BeanFactory和FactoryBean的区别、Bean的作用域,以及默认的作用域、Bean的生命周期、循环依赖、三级缓存、
【Java面试题汇总】Spring篇(2023版)
|
7天前
|
消息中间件 存储 前端开发
面试官:说说停止线程池的执行流程?
面试官:说说停止线程池的执行流程?
27 2
面试官:说说停止线程池的执行流程?
|
29天前
|
Java 数据库连接 Spring
后端框架入门超详细 三部曲 Spring 、SpringMVC、Mybatis、SSM框架整合案例 【爆肝整理五万字】
文章是关于Spring、SpringMVC、Mybatis三个后端框架的超详细入门教程,包括基础知识讲解、代码案例及SSM框架整合的实战应用,旨在帮助读者全面理解并掌握这些框架的使用。
后端框架入门超详细 三部曲 Spring 、SpringMVC、Mybatis、SSM框架整合案例 【爆肝整理五万字】
|
1月前
|
存储 缓存 Java
面试问Spring循环依赖?今天通过代码调试让你记住
该文章讨论了Spring框架中循环依赖的概念,并通过代码示例帮助读者理解这一概念。
面试问Spring循环依赖?今天通过代码调试让你记住
|
1月前
|
XML JSON 数据库
SpringMVC入门到实战------七、RESTful的详细介绍和使用 具体代码案例分析(一)
这篇文章详细介绍了RESTful的概念、实现方式,以及如何在SpringMVC中使用HiddenHttpMethodFilter来处理PUT和DELETE请求,并通过具体代码案例分析了RESTful的使用。
SpringMVC入门到实战------七、RESTful的详细介绍和使用 具体代码案例分析(一)