Springboot sentiment edify-web configuration (i)

Source: Internet
Author: User
Tags static class

To undertake the former Wen springboot sentiment edify [email protected] annotation analysis, in the previous article on the basis of the explanation of the Web-related configuration

Environment Package Dependencies

The pom.xml introduction of Web Dependency in the file, fried chicken simple, as follows

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

The above three-line dependency code completes the configuration of the Web environment, where you can run the main () method directly

package com.example.demospringbootweb;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class DemoSpringbootWebApplication {    public static void main(String[] args) {        SpringApplication.run(DemoSpringbootWebApplication.class, args);    }}

The default service is mounted in a tomcat container with a port of 8080. So you can access the http://127.0.0.1:8080 directly through the link to get the following pages (the effect of the index page is not configured)

Application port and Context configuration

This article will explain the specific configuration and parsing of the port and context path in the underlying mountain above. A simple step operation is now attached

Create a application-servlet.properties file specifically for configuring app services

#server application configserver.port=9001server.servlet.context-path=/demoWeb

Specify the active profile in the application.properties file for the above file to take effect

spring.profiles.active=servlet

In order to make the interface slightly friendlier, introduce the index.html file, placed in the static directory, as follows

Continue running the corresponding main () function to access the Http://127.0.0.1:9001/demoWeband get the following results

SOURCE Analysis

With regard to the configuration of the containers such as Tomcat, Springboot uses the embeddedwebserverfactorycustomizerautoconfiguration and Servletwebserverfactoryautoconfiguration two classes are complete. The author of these two classes for a simple analysis

Embeddedwebserverfactorycustomizerautoconfiguration

View its internal source code directly, as follows

@Configuration@EnableConfigurationProperties(ServerProperties.class)public class EmbeddedWebServerFactoryCustomizerAutoConfiguration {}

The main introduction of the serverproperties configuration class, which is to read the spring context in the beginning of the server -based properties, a simple look at

@ConfigurationProperties (prefix = "Server", Ignoreunknownfields = true) public class Serverproperties {@ConditionalOnCl        ({tomcat.class, upgradeprotocol.class}) public static class Tomcatwebserverfactorycustomizerconfiguration { @Bean Public Tomcatwebserverfactorycustomizer tomcatwebserverfactorycustomizer (Environment environ ment, serverproperties serverproperties) {return new Tomcatwebserverfactorycustomizer (Environment, ServerPrope        Rties);     }}/** * Nested configuration if Jetty is being used. */@Configuration @ConditionalOnClass ({server.class, Loader.class, webappcontext.class}) public static class Je ttywebserverfactorycustomizerconfiguration {@Bean public jettywebserverfactorycustomizer jettywebserverfact Orycustomizer (Environment environment, Serverproperties Serverproperties) {return new Jettyweb       Serverfactorycustomizer (Environment, serverproperties); }}/** * Nested configuration if Undertow is being used. */@Configuration @ConditionalOnClass ({undertow.class, sslclientauthmode.class}) public static class Undertowwe bserverfactorycustomizerconfiguration {@Bean public undertowwebserverfactorycustomizer UNDERTOWWEBSERVERFAC Torycustomizer (Environment environment, Serverproperties Serverproperties) {return new Underto        Wwebserverfactorycustomizer (Environment, serverproperties); }    }}

The Port/servlet.context-path in the sample is saved in the serverproperties object, the property of the internal properties of this article is not expanded, readers can read the source of their own.
It is known from the simple code above that the automatic configuration class mainly creates different application containers based on the CLASSPATH environment, and that the default Springboot integration is Tomcat. We are here to focus on the next Tomcatwebserverfactorycustomizer class, which will be mentioned below

Servletwebserverfactoryautoconfiguration

The specific Servletwebserver container configuration is created through the servletwebserverfactoryautoconfiguration , because the code is too long the author is divided into several parts to explain

First look at the note

@Configuration@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)@ConditionalOnClass(ServletRequest.class)@ConditionalOnWebApplication(type = Type.SERVLET)@EnableConfigurationProperties(ServerProperties.class)@Import({ ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class,        ServletWebServerFactoryConfiguration.EmbeddedTomcat.class,        ServletWebServerFactoryConfiguration.EmbeddedJetty.class,        ServletWebServerFactoryConfiguration.EmbeddedUndertow.class })public class ServletWebServerFactoryAutoConfiguration {}

In order for this automatic configuration to take effect, the servlet environment-dependent classes that exist in the environment must be classpath ServletRequest.class , which generally introduces the beginning of the starter-web section to meet the

Creating the Webserverfactory Class

    @Bean    public ServletWebServerFactoryCustomizer servletWebServerFactoryCustomizer(            ServerProperties serverProperties) {        return new ServletWebServerFactoryCustomizer(serverProperties);    }    @Bean    @ConditionalOnClass(name = "org.apache.catalina.startup.Tomcat")    public TomcatServletWebServerFactoryCustomizer tomcatServletWebServerFactoryCustomizer(            ServerProperties serverProperties) {        return new TomcatServletWebServerFactoryCustomizer(serverProperties);    }

These two bean classes and Tomcatwebserverfactorycustomizer in the above are very similar, but after careful reading of the source found that this is only the Tomcat configuration of the division of Processing, summarized as follows

    • Tomcatwebserverfactorycustomizer configures the primary information for Tomcat, including Remoteipvalue, connector (maximum/minimum acceptable thread, maximum acceptable head size, and so on), uriencoding, ConnectionTimeout, maxconnection and other attributes
    • Tomcatservletwebserverfactorycustomizer Configure additional information for Tomcat, Redirectcontextroot (whether to forward when the root context is requested, true if the forwarding path is/demoweb/) and userelativeredirects (whether to use relative paths) and other paths to jump problem processing
    • Servletwebserverfactorycustomizer mainly configures Tomcat's servlet information, including port, context path, application name, session configuration, initial variables carried by servlet, etc.

Through the above three bean classes basically completed the basic Tomcat configuration, which is the implementation of the Webserverfactorycustomizer interface class, then who will be unified call to complete the above configuration?

1. First introduced the Webserverfactory factory class, this point can be directly seen by the above @Import introduced by the embeddedtomcat analysis can be

    @Configuration    @ConditionalOnClass({ Servlet.class, Tomcat.class, UpgradeProtocol.class })    @ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT)    public static class EmbeddedTomcat {        @Bean        public TomcatServletWebServerFactory tomcatServletWebServerFactory() {            return new TomcatServletWebServerFactory();        }    }

The tomcatservletwebserverfactory Tomcat container is created, and the rest of the web container readers can analyze their own

2. Finally through the Beanpostprocessor interface to complete the corresponding container initialization
The Beanpostprocessorsregistrar class, introduced by @Import , registered the webserverfactorycustomizerbeanpostprocessor class to complete the appropriate Tomcat personalization configuration

    Before initializing the above Webserverfactory object, operate public object Postprocessbeforeinitialization (object bean, String beanname) throws B eansexception {if (bean instanceof webserverfactory) {this.postprocessbeforeinitialization (WebServerF        actory) bean);    } return bean; }//Call all objects that implement the Webserverfactorycustomizer interface private void Postprocessbeforeinitialization (Webserverfactory webserverf Actory) {((callbacks) Lambdasafe.callbacks (Webserverfactorycustomizer.class, This.getcustomizers (), WebServerFacto Ry, new Object[0]). Withlogger (Webserverfactorycustomizerbeanpostprocessor.class)). Invoke ((Customizer), {C        Ustomizer.customize (webserverfactory);    }); }//Find all the types in the current Bean factory as Webserverfactorycustomizer interface object collection Private collection<webserverfactorycustomizer<?>& Gt Getcustomizers () {if (this.customizers = = null) {this.customizers = new ArrayList (THIS.GETWEBSERVERFAC            Torycustomizerbeans ()); This.custOmizers.sort (annotationawareordercomparator.instance);        This.customizers = Collections.unmodifiablelist (this.customizers);    } return this.customizers; } private collection<webserverfactorycustomizer<?>> Getwebserverfactorycustomizerbeans () {return th    Is.beanFactory.getBeansOfType (Webserverfactorycustomizer.class, False, False). values (); }

The detailed analysis of the above code comments, in fact, is also very simple and at a glance, so if users want to personalize on Tomcat, you can implement the Webserverfactorycustomizer interface and register to the Bean factory

@Configurationpublic MyWebServerFactoryCustomizer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>{    @Override    public void customize(ConfigurableServletWebServerFactory factory) {        PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();        // do personal binding    }}
Summary

This article only describes the configuration of Tomcat and gives an example of its Port/contextpath application configuration, and more configuration readers can implement the server -prefixed configuration with springboot and implement it by themselves Webserverfactorycustomizer interface to implement

Springboot sentiment edify-web configuration (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.