Spring Boot -- 嵌入式Servlet容器

188 阅读12分钟

文章目录


1. 概述

Spring MVC中需要配置本地的Tomcat服务器,项目才能够在服务器上运行。而在Spring Boot中并没有配置本地的服务器,同样也可以运行项目。这是因为Spring Boot内置了Tomcat容器,创建Spring Boot项目时,pom.xml中的依赖项只需要引入下面的starter即可:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

而spring-boot-starter-web中就引入了Tomcat相关的依赖,所以无需额外的配置就可以使用Spring Boot内置的Tomcat。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>

具体的依赖图如下:


在这里插入图片描述


2. 定制和修改配置

既然Spring Boot内置了Tomcat容器,并且在项目启动的时候就创建了容器供程序使用,那么能否修改容器相关的配置呢?当然是可以的,修改的方法有如下两种:

2.1 修改配置文件

server.port=8081
server.context‐path=/crud
server.tomcat.uri‐encoding=UTF‐8

//通用的Servlet容器设置
server.xxx

//Tomcat的设置
server.tomcat.xxx

application.xml中修改server.xxxx本质上修改的是ServerProperties类中的属性,它的定义如下

@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
public class ServerProperties
      implements EmbeddedServletContainerCustomizer, EnvironmentAware, Ordered {}

类中的Tomcat属性实际上是new了一个Tomcat对象:

private final Tomcat tomcat = new Tomcat();

Tomcat是它的一个静态内部类,定义如下:

public static class Tomcat {
		private final Accesslog accesslog = new Accesslog();

		private String internalProxies = &quot;10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|&quot; // 10/8
				+ &quot;192\\.168\\.\\d{1,3}\\.\\d{1,3}|&quot; // 192.168/16
				+ &quot;169\\.254\\.\\d{1,3}\\.\\d{1,3}|&quot; // 169.254/16
				+ &quot;127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|&quot; // 127/8
				+ &quot;172\\.1[6-9]{1}\\.\\d{1,3}\\.\\d{1,3}|&quot; // 172.16/12
				+ &quot;172\\.2[0-9]{1}\\.\\d{1,3}\\.\\d{1,3}|&quot;
				+ &quot;172\\.3[0-1]{1}\\.\\d{1,3}\\.\\d{1,3}&quot;;

		private String protocolHeader;
		private String protocolHeaderHttpsValue = &quot;https&quot;;
		private String portHeader = &quot;X-Forwarded-Port&quot;;
		private String remoteIpHeader;
		private File basedir;
		private int backgroundProcessorDelay = 30; 
		private int maxThreads = 0; 
		private int minSpareThreads = 0; 
		private int maxHttpPostSize = 0;
		private int maxHttpHeaderSize = 0; 
		private Boolean redirectContextRoot;
		private Charset uriEncoding;
		private int maxConnections = 0;
		private int acceptCount = 0;
    ...
}

Tomcat类中定义了如上所示的多个配置属性,在配置文件中通过server.tomcat.xxx就可以进行Tomcat相关配置的修改。

2.2 自定义EmbeddedServletContainerCustomize

EmbeddedServletContainerCustomize是嵌入式的Servlet容器的定制器,通过它可以修改Servlet容器的配置。由上面可知ServerProperties类本身也是实现了EmbeddedServletContainerCustomizer接口,因此,我们也可以通过接口的实现类来修改容器的配置。接口的定义如下:

public interface EmbeddedServletContainerCustomizer {
	/**
	 * Customize the specified {@link ConfigurableEmbeddedServletContainer}.
	 * @param container the container to customize
	 */
	void customize(ConfigurableEmbeddedServletContainer container);

}

实现这个接口只需要重写其中的customize()即可。

@Bean 
public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer(){
    return new EmbeddedServletContainerCustomizer() {
        //定制嵌入式的Servlet容器相关的规则
        @Override
        public void customize(ConfigurableEmbeddedServletContainer container) {
            container.setPort(8083);
        }
    };
}

注意一定要使用@Bean将其加入到容器中。例如,上面重新设置了Tomcat的启动端口,项目启动后控制台输出:

2020-06-18 15:09:32.050  INFO 9776 s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8083 (http)

3. 注册Servlet三大组件

由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器,从而最终启动SpringBoot的web应用,没有web.xml文件。注册三大组件用以下方式:

  • ServletRegistrationBean
  • FilterRegistrationBean
  • ServletListenerRegistrationBean
@Configuration
public class MyServerConfig {
    //注册三大组件
    @Bean
    public ServletRegistrationBean myServlet() {
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(), "/myServlet");
        registrationBean.setLoadOnStartup(1);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean myFilter() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new MyFilter());
        registrationBean.setUrlPatterns(Arrays.asList("/hello", "/myServlet"));
        return registrationBean;
    }

    @Bean
    public ServletListenerRegistrationBean myListener() {
        ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());
        return registrationBean;
    }
}

当注册之后,重新启动项目,控制台输出如下信息。从中可以看出,自定义的Sevlert和Filter已经被成功的注册到了Spring Boot的ioc容器中。


在这里插入图片描述


4. DispatcherServlet的自动配置

上面实现了定制的Servlet容器,并注册了Servlet相关的三大组件,那么Spring Boot是否也是使用同样的方法来进行注册的呢?答案当然是肯定的!例如,SpringBoot帮我们自动配置SpringMVC的时候,就会自动的注册SpringMVC的前端控制器DispatcherServlet。找到它对应的实现类DispatcherServletAutoConfiguration,其中有个静态内部类DispatcherServletRegistrationConfiguration,类中的方法dispatcherServletRegistration()就是用来注册DispatcherServlet,方式和上面讲到的是一样的。

@Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)
@ConditionalOnBean(value = DispatcherServlet.class, name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public ServletRegistrationBean dispatcherServletRegistration(
    DispatcherServlet dispatcherServlet) {
    ServletRegistrationBean registration = new ServletRegistrationBean(
        dispatcherServlet, this.serverProperties.getServletMapping());
    registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
    registration.setLoadOnStartup(
        this.webMvcProperties.getServlet().getLoadOnStartup());
    if (this.multipartConfig != null) {
        registration.setMultipartConfig(this.multipartConfig);
    }
    return registration;
}

4. 其他Servlet容器

前面定制Servlet容器时使用的ConfigurableEmbeddedServletContainer,而它是一个接口,接口的实现类有:
在这里插入图片描述
它包含有:

  • TomcatEmbeddedServletContainerFactory
    -JettyEmbeddedServletContainerFactory
  • UndertowEmbeddedServletContainerFactory

通过这三个工厂方法类就可以创建相应的Servlet容器,那么如何切换为其他的容器呢?前面说到,Spring Boot默认使用Tomcat是因为引入的依赖spring-boot-starter-web本身又依赖spring-boot-starter-tomcat,因此它默认使用Tomcat容器。

而容器间的切换,同样也可以通过修改pom.xml中的依赖来解决。例如,使用Jetty容器只需要将默认的Tomcat排除出去,然后导入Jetty相关的依赖即可。

<!‐‐ 引入web模块 ‐‐>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring‐boot‐starter‐web</artifactId>
    <!‐‐ 排除使用Tomcat ‐‐>
    <exclusions>
        <exclusion>
            <artifactId>spring‐boot‐starter‐tomcat</artifactId>
            <groupId>org.springframework.boot</groupId>
        </exclusion>
    </exclusions>
</dependency>

<!‐‐ 引入其他的Servlet容器 ‐‐>
<dependency>
    <artifactId>spring‐boot‐starter‐jetty</artifactId>
    <groupId>org.springframework.boot</groupId>
</dependency>

同样可以切换为Undertow:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring‐boot‐starter‐web</artifactId>
    <exclusions>
        <exclusion>
            <artifactId>spring‐boot‐starter‐tomcat</artifactId>
            <groupId>org.springframework.boot</groupId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <artifactId>spring‐boot‐starter‐undertow</artifactId>
    <groupId>org.springframework.boot</groupId>
</dependency>

5. 嵌入式Servlet容器的自动配置原理

首先找到相关的类定义,源码定义如下:

@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@ConditionalOnWebApplication
@Import(BeanPostProcessorsRegistrar.class)
public class EmbeddedServletContainerAutoConfiguration {}

其中@Import(BeanPostProcessorsRegistrar.class)表示导入BeanPostProcessorsRegistrar,它用于向容器中导入一些组件。它实际导入了EmbeddedServletContainerCustomizerBeanPostProcessor:后置处理器,用于在bean初始化前后(创建完对象,还没赋值赋值)执行初始化工作。

其中有关Tomcat容器的源码如下:

@Configuration
@ConditionalOnClass({ Servlet.class, Tomcat.class })
@ConditionalOnMissingBean(value = EmbeddedServletContainerFactory.class, search = SearchStrategy.CURRENT)
public static class EmbeddedTomcat {

    @Bean
    public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() {
        return new TomcatEmbeddedServletContainerFactory();
    }

}

@ConditionalOnClass({ Servlet.class, Tomcat.class })用于判断当前是否引入了Tomcat依赖,即前面说到容器切换时相关的依赖项。@ConditionalOnMissingBean判断当前容器没有用户自己定义EmbeddedServletContainerFactory,即嵌入式的Servlet容器工厂。

其中,EmbeddedServletContainerFactory定义如下:

public interface EmbeddedServletContainerFactory {

	EmbeddedServletContainer getEmbeddedServletContainer(ServletContextInitializer... initializers);

}

getEmbeddedServletContainer()用于获取嵌入式的Servlet容器,返回的是EmbeddedServletContainer,它是一个接口,对应的实现类有:

在这里插入图片描述

因此,使用相应的实现类就可以获取到不同的Servlet容器。以TomcatEmbeddedServletContainerFactor为例看一下如何功通过工厂来获取容器。

@Override
public EmbeddedServletContainer getEmbeddedServletContainer(
    ServletContextInitializer... initializers) {
    
    // 创建一个Tomcat
    Tomcat tomcat = new Tomcat();
    
    // 配置Tomcat的基本环节
    File baseDir = (this.baseDirectory != null ? this.baseDirectory
                    : createTempDir("tomcat"));
    tomcat.setBaseDir(baseDir.getAbsolutePath());
    Connector connector = new Connector(this.protocol);
    tomcat.getService().addConnector(connector);
    customizeConnector(connector);
    tomcat.setConnector(connector);
    tomcat.getHost().setAutoDeploy(false);
    configureEngine(tomcat.getEngine());
    for (Connector additionalConnector : this.additionalTomcatConnectors) {
        tomcat.getService().addConnector(additionalConnector);
    }
    prepareContext(tomcat.getHost(), initializers);
    
    //将配置好的Tomcat作为getTomcatEmbeddedServletContainer的方法参数,得到一个EmbeddedServletContainer;并且启动Tomcat服务器
    return getTomcatEmbeddedServletContainer(tomcat);
}

getTomcatEmbeddedServletContainer()接收一个Tomcat对象,最后调用TomcatEmbeddedServletContainer的构造方法来返回TomcatEmbeddedServletContainer实例。

protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(Tomcat tomcat) {
	return new TomcatEmbeddedServletContainer(tomcat, getPort() >= 0);
}

对应的构造方法如下,初始化完相关的属性后调用了initialize()

public TomcatEmbeddedServletContainer(Tomcat tomcat, boolean autoStart) {
	Assert.notNull(tomcat, "Tomcat Server must not be null");
	this.tomcat = tomcat;
	this.autoStart = autoStart;
	initialize();
}

initialize()的定义如下:

private void initialize() throws EmbeddedServletContainerException {
    TomcatEmbeddedServletContainer.logger.info("Tomcat initialized with port(s): " + getPortsDescription(false));
    
    synchronized (this.monitor) {
        try {
            addInstanceIdToEngineName();
            try {
                // Remove service connectors to that protocol binding doesn't happen
                // yet
                removeServiceConnectors();

                // Start the server to trigger initialization listeners
                this.tomcat.start();

                // We can re-throw failure exception directly in the main thread
                rethrowDeferredStartupExceptions();

                Context context = findContext();
                try {
                    ContextBindings.bindClassLoader(context, getNamingToken(context),
                                                    getClass().getClassLoader());
                }
                catch (NamingException ex) {
                    // Naming is not enabled. Continue
                }

                // Unlike Jetty, all Tomcat threads are daemon threads. We create a
                // blocking non-daemon to stop immediate shutdown
                startDaemonAwaitThread();
            }
            catch (Exception ex) {
                containerCounter.decrementAndGet();
                throw ex;
            }
        }
        catch (Exception ex) {
            throw new EmbeddedServletContainerException(
                "Unable to start embedded Tomcat", ex);
        }
    }
}

其中最重要的就是调用了start()开启了Tomcat容器。

至此,我们知道了Spring Boot如何自动配置Servlet容器。那么前面定制的EmbeddedServletContainerCustomizer中对于配置的修改是如何生效的呢?前面讲到定制器导入了EmbeddedServletContainerCustomizerBeanPostProcessor,,源码如下:

public class EmbeddedServletContainerCustomizerBeanPostProcessor
      implements BeanPostProcessor, BeanFactoryAware {

   private ListableBeanFactory beanFactory;

   private List<EmbeddedServletContainerCustomizer> customizers;

   @Override
   public void setBeanFactory(BeanFactory beanFactory) {
      Assert.isInstanceOf(ListableBeanFactory.class, beanFactory,
            "EmbeddedServletContainerCustomizerBeanPostProcessor can only be used "
                  + "with a ListableBeanFactory");
      this.beanFactory = (ListableBeanFactory) beanFactory;
   }
	
   
   // 初始化之前
   @Override
   public Object postProcessBeforeInitialization(Object bean, String beanName)
         throws BeansException {
      //如果当前初始化的是一个ConfigurableEmbeddedServletContainer类型的组件
      if (bean instanceof ConfigurableEmbeddedServletContainer) {
         postProcessBeforeInitialization((ConfigurableEmbeddedServletContainer) bean);
      }
      return bean;
   }

   @Override
   public Object postProcessAfterInitialization(Object bean, String beanName)
         throws BeansException {
      return bean;
   }

   private void postProcessBeforeInitialization(
         ConfigurableEmbeddedServletContainer bean) {
      //获取所有的定制器,调用每一个定制器的customize方法来给Servlet容器进行属性赋值;
      for (EmbeddedServletContainerCustomizer customizer : getCustomizers()) {
         customizer.customize(bean);
      }
   }

   private Collection<EmbeddedServletContainerCustomizer> getCustomizers() {
      if (this.customizers == null) {
         // Look up does not include the parent context
         this.customizers = new ArrayList<EmbeddedServletContainerCustomizer>(
               //从容器中获取所有这个类型的组件:EmbeddedServletContainerCustomizer
			   //定制Servlet容器,给容器中可以添加一个EmbeddedServletContainerCustomizer类型的组件
               this.beanFactory
                     .getBeansOfType(EmbeddedServletContainerCustomizer.class,
                           false, false)
                     .values());
         Collections.sort(this.customizers, AnnotationAwareOrderComparator.INSTANCE);
         this.customizers = Collections.unmodifiableList(this.customizers);
      }
      return this.customizers;
   }

}

总结一下,Servlet容器自动配置的步骤为:

  • SpringBoot根据导入的依赖情况,给容器中添加相应EmbeddedServletContainerFactory,如TomcatEmbeddedServletContainerFactory
  • 容器中某个组件要创建对象就会调用后置处理器EmbeddedServletContainerCustomizerBeanPostProcessor;
    只要是嵌入式的Servlet容器工厂,后置处理器就工作;
  • 后置处理器,从容器中获取所有的EmbeddedServletContainerCustomizer,调用定制器的定制方法

6. 嵌入式Servlet容器启动原理

上面看完了Spring Boot中Servlet容器的自动配置后知道,当我们想要使用某一个容器时只需要在pomx.xml中导入相关的依赖,Spring Boot会自动帮我们配置。那么什么时候创建嵌入式的Servlet容器工厂?什么时候获取嵌入式的Servlet容器并启动容器呢?

Spring Boot 项目创建后生成的主函数如下:

@SpringBootApplication
public class SpringBoot04WebRestfulcrudApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBoot04WebRestfulcrudApplication.class, args);
    }
}

当启动项目时,执行首先获取指定的Servlet容器。获取嵌入式的Servlet容器工厂的步骤为:

  • SpringBoot应用启动运行run(),即调用SpringApplication.run(),它的定义如下:

    public static ConfigurableApplicationContext run(Object source, String... args) {
        return run(new Object[] { source }, args);
    }
    

    它又调用了类内的run(),定义如下:

    public static ConfigurableApplicationContext run(Object[] sources, String[] args) {
        return new SpringApplication(sources).run(args);
    }
    

    最终执行的是下面的run()

    public ConfigurableApplicationContext run(String... args) {
    		StopWatch stopWatch = new StopWatch();
    		stopWatch.start();
    		ConfigurableApplicationContext context = null;
    		FailureAnalyzers analyzers = null;
    		configureHeadlessProperty();
    		SpringApplicationRunListeners listeners = getRunListeners(args);
    		listeners.starting();
    		try {
    			ApplicationArguments applicationArguments = new DefaultApplicationArguments(
    					args);
    			ConfigurableEnvironment environment = prepareEnvironment(listeners,
    					applicationArguments);
    			Banner printedBanner = printBanner(environment);
                // 创建一个ApplicationContext容器
    			context = createApplicationContext();
    			analyzers = new FailureAnalyzers(context);
                // 准备容器中所需的东西
    			prepareContext(context, environment, listeners, applicationArguments,
    					printedBanner);
    			refreshContext(context);
    			afterRefresh(context, applicationArguments);
    			listeners.finished(context, null);
    			stopWatch.stop();
    			if (this.logStartupInfo) {
    				new StartupInfoLogger(this.mainApplicationClass)
    						.logStarted(getApplicationLog(), stopWatch);
    			}
    			return context;
    		}
    		catch (Throwable ex) {
    			handleRunFailure(context, listeners, analyzers, ex);
    			throw new IllegalStateException(ex);
    		}
    	}
    
  • createApplicationContext():创建IOC容器,如果是web应用则创建AnnotationConfigEmbeddedWebApplacation的IOC容器,如果不是,则创建AnnotationConfigApplication的IOC容器

    protected ConfigurableApplicationContext createApplicationContext() {
        Class<?> contextClass = this.applicationContextClass;
        if (contextClass == null) {
            try {
                // 利用反射机制,使用webEnvironment来根据不同的应用场景创建不同的容器
                contextClass = Class.forName(this.webEnvironment
                                             ? DEFAULT_WEB_CONTEXT_CLASS : DEFAULT_CONTEXT_CLASS);
            }
            catch (ClassNotFoundException ex) {
                throw new IllegalStateException(
                    "Unable create a default ApplicationContext, "
                    + "please specify an ApplicationContextClass",
                    ex);
            }
        }
        return (ConfigurableApplicationContext) BeanUtils.instantiate(contextClass);
    }
    
  • refreshContext(context):返回到ConfigurableApplicationContext()中,当创建好针对具体应用场景的容器后,调用refreshContext()刷新Ioc容器,刷新操作指创建IOC容器对象并初始化容器,创建容器中的每一
    个组件;如果是web应用创建AnnotationConfigEmbeddedWebApplicationContext,否则创建AnnotationConfigApplicationContext

    private void refreshContext(ConfigurableApplicationContext context) {
        refresh(context);
        if (this.registerShutdownHook) {
            try {
                context.registerShutdownHook();
            }
            catch (AccessControlException ex) {
                // Not allowed in some environments.
            }
        }
    }
    
  • refresh(context):刷新刚才创建好的ioc容器

    protected void refresh(ApplicationContext applicationContext) {
        Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
        ((AbstractApplicationContext) applicationContext).refresh();
    }
    
  • onRefresh():这里调用的是抽象父类AbstractApplicationContext类的子类EmbeddedWebApplicationContext的onRefresh方法

    @Override
    protected void onRefresh() {
        super.onRefresh();
        try {
            createEmbeddedServletContainer();
        }
        catch (Throwable ex) {
            throw new ApplicationContextException("Unable to start embedded container",
                                                  ex);
        }
    }
    
  • Ioc容器会创建嵌入式的Servlet容器;createEmbeddedServletContainer();

  • 获取嵌入式的Servlet容器工厂:

    EmbeddedServletContainerFactory containerFactory = getEmbeddedServletContainerFactory();
    从ioc容器中获取EmbeddedServletContainerFactory 组件;TomcatEmbeddedServletContainerFactory创建
    对象,触发后置处理器,然后后置处理器获取所有的定制器来先定制Servlet容器的相关配置

    private void createEmbeddedServletContainer() {
        EmbeddedServletContainer localContainer = this.embeddedServletContainer;
        ServletContext localServletContext = getServletContext();
        if (localContainer == null && localServletContext == null) {    
            //获取嵌入式Servlet容器工厂
            EmbeddedServletContainerFactory containerFactory = getEmbeddedServletContainerFactory();          
            //根据容器工厂获取对应嵌入式Servlet容器
            this.embeddedServletContainer = containerFactory
                .getEmbeddedServletContainer(getSelfInitializer());
        }
        else if (localServletContext != null) {
            try {
                getSelfInitializer().onStartup(localServletContext);
            }
            catch (ServletException ex) {
                throw new ApplicationContextException("Cannot initialize servlet context", ex);
            }
        }
        initPropertySources();
    }
    
  • 使用容器工厂获取嵌入式的Servlet容器:

    this.embeddedServletContainer = containerFactory.getEmbeddedServletContainer(getSelfInitializer());
    
  • 嵌入式的Servlet容器创建对象并启动Servlet容器;先启动嵌入式的Servlet容器,再将ioc容器中剩下没有创建出的对象获取出来

    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
        // Initialize conversion service for this context.
        if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
            beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
            beanFactory.setConversionService(
                beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
        }
    
        // Register a default embedded value resolver if no bean post-processor
        // (such as a PropertyPlaceholderConfigurer bean) registered any before:
        // at this point, primarily for resolution in annotation attribute values.
        if (!beanFactory.hasEmbeddedValueResolver()) {
            beanFactory.addEmbeddedValueResolver(new StringValueResolver() {
                @Override
                public String resolveStringValue(String strVal) {
                    return getEnvironment().resolvePlaceholders(strVal);
                }
            });
        }
    
        // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
        String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
        for (String weaverAwareName : weaverAwareNames) {
            getBean(weaverAwareName);
        }
    
        // Stop using the temporary ClassLoader for type matching.
        beanFactory.setTempClassLoader(null);
    
        // Allow for caching all bean definition metadata, not expecting further changes.
        beanFactory.freezeConfiguration();
    
        // Instantiate all remaining (non-lazy-init) singletons.
        beanFactory.preInstantiateSingletons();
    }
    

7. 使用外置Servlet容器

7.1 引入

既然Spring Tomcat已经在内部集成了常用的三个Servlet容器,那是否就适合与所有的应用场景呢?其实不然,Spring Boot内置的Servlet容器默认不支持JSP。。而且优化定制也比较麻烦。因此,当我们需要开发使用JSP的项目时,最好使用外置的支持JSP的容器,而Spring Boot也提供了相关的支持。

要想使用外置的Tomcat,需要首先安装Tomcat服务器,然后在创建项目的时候使用war包的形式进行打包。

7.2 使用步骤

  • 创建web项目,打包方式选择war
    在这里插入图片描述

  • 将Spring Boot内置的Tomcat设置为provided

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring‐boot‐starter‐tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    
  • 编写一个SpringBootServletInitializer的子类,并调用configure方法,如果是IDEA,项目创建后会自动创建该类

    public class ServletInitializer extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    //传入SpringBoot应用的主程序
    return application.sources(SpringBoot04WebJspApplication.class);
    }
    }
    
  • 配置外置的Tomcat,启动服务器运行项目即可

7.3 原理分析

当以jar的打包形式创建项目后,执行Spring Boot主类的main(),系统会启动Ioc容器,创建嵌入式的Servlet容器等一系列操作执行程序。当以war包形式创建项目后启动服务器时,服务器会启动SpringBoot应SpringBootServletInitializer,它会启动Ioc容器,然后执行后续的操作。

之所以需要创建SpringBootServletInitializer的子类,并重写configure方法,是因为Servlet3.0规范中定义了相关的规则:

  • 服务器启动(web应用启动)会创建当前web应用里面每一个jar包里面ServletContainerInitializer实例:
  • ServletContainerInitializer的实现放在jar包的META-INF/services文件夹下,有一个名为
    javax.servlet.ServletContainerInitializer的文件,内容就是ServletContainerInitializer的实现类的全类名
  • 还可以使用@HandlesTypes,在应用启动的时候加载我们感兴趣的类;

启动流程:

流程:

  • 开启配置好的Tomcat

  • Spring的web模块里面有javax.servlet.ServletContainerInitializer这个文件,文件的内容是org.springframework.web.SpringServletContainerInitializer,该类的源码如下:

    @HandlesTypes(WebApplicationInitializer.class)
    public class SpringServletContainerInitializer implements ServletContainerInitializer {
        @Override
        public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
            throws ServletException {
    
            List<WebApplicationInitializer> initializers = new LinkedList<>();
    
            if (webAppInitializerClasses != null) {
                for (Class<?> waiClass : webAppInitializerClasses) {
                    if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
                        WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
                        try {
                            initializers.add((WebApplicationInitializer)
                                             ReflectionUtils.accessibleConstructor(waiClass).newInstance());
                        }
                        catch (Throwable ex) {
                            throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
                        }
                    }
                }
            }
    
            if (initializers.isEmpty()) {
                servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
                return;
            }
    
            servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
            AnnotationAwareOrderComparator.sort(initializers);
            for (WebApplicationInitializer initializer : initializers) {
                initializer.onStartup(servletContext);
            }
        }
    }
    
  • SpringServletContainerInitializer将@HandlesTypes(WebApplicationInitializer.class)标注的所有这个类型
    的类都传入到onStartup方法的Set,为这些WebApplicationInitializer类型的类创建实例

  • 每一个WebApplicationInitializer都调用自己的onStartup(),相当于SpringBootServletInitializer的类会被创建对象,并执行onStartup()

  • SpringBootServletInitializer实例执行onStartup的时候会createRootApplicationContext,创建容器

    protected WebApplicationContext createRootApplicationContext(
        ServletContext servletContext) {
        //1、创建SpringApplicationBuilder
        SpringApplicationBuilder builder = createSpringApplicationBuilder();
        StandardServletEnvironment environment = new StandardServletEnvironment();
        environment.initPropertySources(servletContext, null);
        builder.environment(environment);
        builder.main(getClass());
        ApplicationContext parent = getExistingRootWebApplicationContext(servletContext);
        if (parent != null) {
            this.logger.info("Root context already created (using as parent).");
            servletContext.setAttribute(
                WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null);
            builder.initializers(new ParentContextApplicationContextInitializer(parent));
        }
        builder.initializers(
            new ServletContextApplicationContextInitializer(servletContext));
        builder.contextClass(AnnotationConfigEmbeddedWebApplicationContext.class);
        //调用configure方法,子类重写了这个方法,将SpringBoot的主程序类传入了进来
        builder = configure(builder);
        //使用builder创建一个Spring应用
        SpringApplication application = builder.build();
        if (application.getSources().isEmpty() && AnnotationUtils
            .findAnnotation(getClass(), Configuration.class) != null) {
            application.getSources().add(getClass());
        }
        Assert.state(!application.getSources().isEmpty(),
                     "No SpringApplication sources have been defined. Either override the "
                     + "configure method or add an @Configuration annotation");
        // Ensure error pages are registered
        if (this.registerErrorPageFilter) {
            application.getSources().add(ErrorPageFilterConfiguration.class);
        }
        //启动Spring应用
        return run(application);
    }
    
  • Spring的应用就启动并且创建IOC容器

    public ConfigurableApplicationContext run(String... args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ConfigurableApplicationContext context = null;
        FailureAnalyzers analyzers = null;
        configureHeadlessProperty();
        SpringApplicationRunListeners listeners = getRunListeners(args);
        listeners.starting();
        try {
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(
                args);
            ConfigurableEnvironment environment = prepareEnvironment(listeners,
                                                                     applicationArguments);
            Banner printedBanner = printBanner(environment);
            context = createApplicationContext();
            analyzers = new FailureAnalyzers(context);
            prepareContext(context, environment, listeners, applicationArguments,
                           printedBanner);
            //刷新IOC容器
            refreshContext(context);
            afterRefresh(context, applicationArguments);
            listeners.finished(context, null);
            stopWatch.stop();
            if (this.logStartupInfo) {
                new StartupInfoLogger(this.mainApplicationClass)
                    .logStarted(getApplicationLog(), stopWatch);
            }
            return context;
        }
        catch (Throwable ex) {
            handleRunFailure(context, listeners, analyzers, ex);
            throw new IllegalStateException(ex);
        }
    }
    

总结:先启动Servlet容器,再启动Spring Boot应用。