[SpringBoot] SpringBoot Servlet container (XI)

Embedded Servlet Container

  Create a SpringBoot Web project, you can see that dependence, SpringBoot use as an embedded Tomcat Servlet container default;

  

  1, customize and modify the embedded Servlet container configuration

    1, modify and server-related configuration (ServerProperties EmbeddedServletContainerCustomizer [also]);

1  # project port
 2  the server.port = 8081
 . 3  # item access path
 . 4  server.servlet.context-path = / Test
 . 5  # Tomcat encoding
 . 6  server.tomcat.uri-encoding = UTF-. 8
 . 7  
. 8  # generic Servlet Container provided
 . 9  # server.xxx
 10  
. 11  # is provided the Tomcat
 12 is # server.tomcat.xxx

    2, write a EmbeddedServletContainerCustomizer: Servlet container custom embedded device; to modify the configuration Servlet container

1  // custom is added to the vessel
 2  @Bean
 . 3 public WebServerFactoryCustomizer < ConfigurableWebServerFactory > webServerFactoryCustomizer () {
 . 4      return new new WebServerFactoryCustomizer < ConfigurableWebServerFactory > () {
 . 5  
. 6          rules associated // custom embedded Servlet container
 . 7          @Override
 . 8          public Customize void (ConfigurableWebServerFactory Factory) {
 . 9              factory.setPort (8083);
 10          }
 . 11      };
 12 is }

   2, replaced by other embedded Servlet Container

    There are three main Embedded Servlet Container: Tomcat, Jetty (support long links), Undertow (does not support JSP)

    a, Tomcat (default)

      Default is introduced into the web using an embedded module as Tomcat Servlet Container;

1 <dependency>
2     <groupId>org.springframework.boot</groupId>
3     <artifactId>spring-boot-starter-web</artifactId>
4 </dependency>

    b、Jetty

 1 <!-- 引入Web模块 -->
 2 <dependency>
 3     <groupId>org.springframework.boot</groupId>
 4     <artifactId>spring-boot-starter-web</artifactId>
 5     <!--<exclusions>-->
 6         <!--<exclusion>-->
 7             <!--<groupId>org.springframework.boot</groupId>-->
 8             <!--<artifactId>spring-boot-starter-tomcat</artifactId>-->
 9         <!--</exclusion>-->
10     <!--</exclusions>-->
11 </dependency>
12 
13 <!-- 引入其他的Servlet容器 -->
14 <dependency>
15     <groupId>org.springframework.boot</groupId>
16     <artifactId>spring-boot-starter-jetty</artifactId>
17 </dependency>

    c、undertow

 1 <!-- 引入Web模块 -->
 2 <dependency>
 3     <groupId>org.springframework.boot</groupId>
 4     <artifactId>spring-boot-starter-web</artifactId>
 5     <!--<exclusions>-->
 6         <!--<exclusion>-->
 7             <!--<groupId>org.springframework.boot</groupId>-->
 8             <!--<artifactId>spring-boot-starter-tomcat</artifactId>-->
 9         <!--</exclusion>-->
10     <!--</exclusions>-->
11 </dependency>
12 
13 <!-- 引入其他的Servlet容器 -->
14 <dependency>
15     <groupId>org.springframework.boot</groupId>
16     <artifactId>spring-boot-starter-undertow</artifactId>
17 </dependency>
View Code

  3, using an external Servlet Container

    Embedded Servlet container: application executable jar labeled

      Advantages: simple, portable;

      Cons: The default does not support JSP, customized optimization is more complex (using the Customizer [ServerProperties, custom WebServerFactoryCustomizer], I have written to create an embedded Servlet container factory WebServerFactoryCustomizer []);

    External Servlet container: --- embodiment the Tomcat application installed outside war package packing;

    step

      a, create a SpringBoot War project;

        

        pom.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5     <modelVersion>4.0.0</modelVersion>
 6 
 7     <groupId>com.test</groupId>
 8     <artifactId>test-springboot-war</artifactId>
 9     <version>1.0-SNAPSHOT</version>
10     <packaging>war</packaging>
11 
12     <parent>
13         <groupId>org.springframework.boot</groupId>
14         <artifactId>spring-boot-starter-parent</artifactId>
15         <version>2.1.8.RELEASE</version>
16     </parent>
17 
18     <properties>
19 
20         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
21         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
22         <java.version>1.8</java.version>
23     </properties>
24 
25     <dependencies>
26 
27         <dependency>
28             <groupId>org.springframework.boot</groupId>
29             <artifactId>spring-boot-starter-web</artifactId>
30         </dependency>
31 
32         <dependency>
33             <groupId>org.springframework.boot</groupId>
34             <artifactId>spring-boot-starter-tomcat</artifactId>
35             <scope>provided</scope>
36         </dependency>
37 
38         <dependency>
39             <groupId>org.springframework.boot</groupId>
40             <artifactId>spring-boot-starter-test</artifactId>
41             <scope>test</scope>
42         </dependency>
43 
44     </dependencies>
45 
46 
47     <!--SpringBoot packing plug, the code can be packaged into an executable jar package -> 
48      < Build > 
49          < plugins > 
50              < plugin > 
51 is                  < the groupId > org.springframework.boot </ the groupId > 
52 is                  < the artifactId > Spring-Boot plugin--maven </ the artifactId > 
53 is              </ plugin > 
54 is          </ plugins > 
55      </ Build > 
56 is  </ Project >
View Code

     b, the embedded Tomcat designated as provided;

1 <dependency>
2     <groupId>org.springframework.boot</groupId>
3     <artifactId>spring-boot-starter-tomcat</artifactId>
4     <scope>provided</scope>
5 </dependency>

    c, you must write a subclass ServletInitializer.java SpringBootServletInitializer and rewrite configure method

 1 package com.test.springboot;
 2 
 3 import org.springframework.boot.builder.SpringApplicationBuilder;
 4 import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
 5 
 6 public class ServletInitializer extends SpringBootServletInitializer {
 7 
 8     @Override
 9     protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
10         return application.sources(Application.class);
11     }
12 
13 } 

  4, an external Servlet containers principle

    jar package: execute a main method of the main class SpringBoot start ioc container, creating embedded Servlet Container;

    war package: start the server, the application server starts SpringBoot] [SpringBootServletInitializer start ioc container;    

    Servlet3.0 (specification): 8.2.4 Shared libraries / runtimes pluggability: Rule:

    1), the server starts (web application launch) will create the current web application inside each jar package which ServletContainerInitializer instance: 

    2), placed under realization ServletContainerInitializer jar package META-INF / services folder, a file named javax.servlet.ServletContainerInitializer, the content is the full class name of the implementation class ServletContainerInitializer 

    3) You can also use @HandlesTypes, we are interested in the class is loaded when the application starts;

    Process

      1) Start Tomcat

      2)、org\springframework\spring-web\4.3.14.RELEASE\spring-web-4.3.14.RELEASE.jar!\META- INF\services\javax.servlet.ServletContainerInitializer:

        Spring's web module inside the file: org.springframework.web.SpringServletContainerInitializer 

      3), SpringServletContainerInitializer the @HandlesTypes (WebApplicationInitializer.class) all labels of this type are passed to the class method onStartup Set>;

        Examples of these types WebApplicationInitializer create classes; 

      4), each WebApplicationInitializer are calling their onStartup;

      5), the equivalent of our SpringBootServletInitializer class is to create objects and perform method onStartup

      6), when SpringBootServletInitializer instance execution onStartup will createRootApplicationContext; create container

 1 protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) {
 2 
 3     //1、创建SpringApplicationBuilder
 4     SpringApplicationBuilder builder = createSpringApplicationBuilder();
 5     builder.main(getClass());
 6     ApplicationContext parent = getExistingRootWebApplicationContext(servletContext);
 7     if (parent != null) {
 8         this.logger.info("Root context already created (using as parent).");
 9         servletContext.setAttribute (the WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null );
 10          builder.initializers ( new new ParentContextApplicationContextInitializer (parent));
 . 11      }
 12 is  
13 is      builder.initializers ( new new ServletContextApplicationContextInitializer (where servletContext));
 14      builder.contextClass (AnnotationConfigServletWebServerApplicationContext. class );
 15  
16      // calls configure method subclass overrides this method, the main afferent SpringBoot came 
. 17      Builder = configure (Builder);
 18 is      //使用builder创建一个Spring应用
19     builder.listeners(new WebEnvironmentPropertySourceInitializer(servletContext));
20 
21     SpringApplication application = builder.build();
22     if (application.getAllSources().isEmpty()
23             && AnnotationUtils.findAnnotation(getClass(), Configuration.class) != null) {
24         application.addPrimarySources(Collections.singleton(getClass()));
25     }
26     Assert.state(!application.getAllSources().isEmpty(),
27             "No SpringApplication sources have been defined. Either override the "
28                     + "configure method or add an @Configuration annotation");
29     // Ensure error pages are registered
30     if (this.registerErrorPageFilter) {
31         application.addPrimarySources(Collections.singleton(ErrorPageFilterConfiguration.class));
32     }
33     //启动Spring应用
34     return run(application);
35 }
View Code

      7), Spring application is started and creates IOC container

 1 public ConfigurableApplicationContext run(String... args) {
 2     StopWatch stopWatch = new StopWatch();
 3     stopWatch.start();
 4     ConfigurableApplicationContext context = null;
 5     Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
 6     configureHeadlessProperty();
 7     SpringApplicationRunListeners listeners = getRunListeners(args);
 8     listeners.starting();
 9     try {
10         ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
11         ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
12         configureIgnoreBeanInfo(environment);
13         Banner printedBanner = printBanner(environment);
14         context = createApplicationContext();
15         exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
16                 new Class[] { ConfigurableApplicationContext.class }, context);
17         prepareContext(context, environment, listeners, applicationArguments, printedBanner);
18 
19         //刷新IOC容器
20         refreshContext(context);
21         afterRefresh(context, applicationArguments);
22         stopWatch.stop();
23         if (this.logStartupInfo) {
24             new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
25         }
26         listeners.started(context);
27         callRunners(context, applicationArguments);
28     }
29     catch (Throwable ex) {
30         handleRunFailure(context, ex, exceptionReporters, listeners);
31         throw new IllegalStateException(ex);
32     }
33 
34     try {
35         listeners.running(context);
36     }
37     catch (Throwable ex) {
38         handleRunFailure(context, ex, exceptionReporters, null);
39         throw new IllegalStateException(ex);
40     }
41     return context;
42 }
View Code

      Start Servlet container, and then start the application SpringBoot

 

 

Guess you like

Origin www.cnblogs.com/h--d/p/12393302.html