[SpringBoot Learning Notes 8] SpringBoot Customized Integration SpringMVC

The previous Blog explored in detail how SpringBoot integrates data sources, from the JDBC level to the data source connection pool level (Druid)On the MyBatis level, we use three encapsulated scene launchers: spring-boot-starter-data-jdbc, druid-spring-boot-starter, mybatis-spring-boot-starter. With SpringBoot's automatic configuration mechanism, we only need to care about the contents of the yml configuration file to operate the database easily and conveniently, which can be said to be very convenient, at least compared to Spring Boot.Integrating MyBatis saves a lot of code and configuration. SpringBoot is also very convenient to integrate SpringMVC, using the spring-boot-starter-web scene launcher.

spring-boot-starter-web scene launcher

spring-boot-starter-web provides us with embedded Servlet containers and Spring MVC dependencies, as well as numerous automatic configurations for Spring MVC that can be used in most Web development scenarios. Spring Boot provides automatic configuration for Spring MVC and adds the following features based on Spring MVC default functionality:

  • ContentNegotiating ViewResolver and BeanNameViewResolver were introduced
  • Support for static resources, including WebJars, and access to static home pages (index.html)
  • Automatically register Converter, GenericConverter, and Formatter (Converter and Formatter)
  • Support for HttpMessageConverters (Message Converters used to convert HTTP requests and responses in Spring MVC)
  • Automatically register MessageCodesResolver (used to define error code generation rules)
  • Automatically use Configurable WebBindingInitializer

As long as we have introduced spring-boot-starter-web into pom.xml in the Spring Boot project, you can use Spring MVC directly for Web development without any configuration. If you're not impressed, you can see my first Spring Boot Blog [SpringBoot Learning Notes 1] Basic SpringBoot concepts and project initialization Spring MVC was actually automatically introduced when the web module was first introduced. The following steps were omitted when comparing Spring's integration with Spring MVC before:

We can concentrate on our logic, and SpringBoot's automatic configuration does it for us.

Principle of SpringMVC Autoconfiguration

Spring Boot abandons traditional xml configuration files and configures them as JavaBean s by configuring classes (labeled @Configuration class, equivalent to an xml configuration file). Spring Boot's automatic configuration of Spring MVC meets most of our needs, but we can also configure classes by customizing them (labeled @Configuration class)Implement WebMvcConfigurer interface to customize Spring MVC configuration, such as interceptor, formatter, view controller, etc.

WebMvcAutoConfiguration Auto Configuration Class

In AutoConfiguration Principle SpringBoot Learning Notes 4) Principles of SpringBoot Autoconfiguration As mentioned in this Blog, some auto-configuration classes are set in META-INF/spring.factories under the spring-boot-autoconfigure-xxx.jar class path, including WebMvcAutoConfiguration

It can help us automate the integration and customization of Spring MVC.

Examples of formatting

Let's take an example and find the formatting converter with the following code:

        public FormattingConversionService mvcConversionService() {
            WebConversionService conversionService = new WebConversionService(this.mvcProperties.getDateFormat());
            return conversionService;

Follow up to see:

public String getDateFormat() {
    return this.dateFormat;

* Date format to use. For instance, `dd/MM/yyyy`. Default
private String dateFormat;

You can see that in our Properties file, we can configure it automatically, and if we configure our own formatting, it will be registered with the Bean and take effect, for example, we can configure rules for date formatting in the configuration file.

Extend Spring MVC capabilities

In the Spring Boot project, we can customize Spring MVC in two forms: expanding the Spring MVC and taking over the Spring MVC in its entirety

Below, we describe the two forms of custom Spring MVC

WebMvcConfigurer is a Java 8-based interface that defines many Spring MVC-related methods, most of which are default-type and are empty implementations. Therefore, we only need to define a configuration class to implement the WebMvcConfigurer interface and override the corresponding methods to customize the configuration of Spring MVC

WebMvcConfigurer interface

If Spring Boot's automatic configuration of Spring MVC does not meet our needs, we can also customize a configuration class for a WebMvcConfigurer type that implements the WebMvcConfigurer interface (label @Configuration, but not @EnableWebMvc annotated class)This not only preserves Spring Boot's automatic configuration of Spring MVC, enjoys the convenience of Spring Boot's automatic configuration, but also adds a customized Spring MVC configuration.

Customize the default configuration of SpringBoot

We can modify SpringBoot's default configuration to customize our implementation. Let's first see what a homepage request would look like if interception was not turned on:

1 Create Controller

We create a Controller jump request for a result:

package com.example.springboot.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

public class ResultController {
    public String loginPage() {
        return "result";

2 Modify custom configuration

Modify the custom configuration so that when a homepage request arrives, it is blocked and then moved to the request for result

package com.example.springboot.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

public class ResultController {
    public String loginPage() {
        return "I'm not the homepage you want to see, I'm a jump customization page,A login page";

3 Request Home Page View Effect

After configuring the custom settings, we request to view the home page again:

Take Over Spring MVC

Full take-over means SpringBoot doesn't need to automatically configure SpringMVC. We configure everything on our own by adding @EnableWebMvc to our configuration class. Full take-over of SpringMVC is not recommended in our development.

Open full take-over effect

Opening a full take-over is easy. We just need to open the annotations in the original custom configuration class:

package com.example.springboot.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
//Implementing the WebMvcConfigurer interface extends SpringMVC capabilities
public class MyMvcConfig implements WebMvcConfigurer {
    public void addViewControllers(ViewControllerRegistry registry) {
        //When accessing'/'or'/index.html', jump directly to the landing page

Request again after full takeover:

Spring Boot's ability to access static resources on the home page is Spring Boot's default Spring MVC configuration, which fails after a full take-over

Principle of full take-over

Why add a comment and the auto-configuration fails? Let's look at the source code:

EnableWebMVC Comment

public @interface EnableWebMvc {

Here we see that it imports a class, so we can go on and see

WebMvcConfigurationSupport class

public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
  // ......

It inherits a parent WebMvcConfiguration Support, so let's review the Webmvc autoconfiguration class

@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
// This annotation means that the auto-configuration class will not take effect until the component is not present in the container
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
    ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {

As a result of this annotation @ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
WebMvcAutoConfiguration Auto Configuration will not work, and WebMvcConfiguration Supports only have the basic features of Spring MVC, so it is too difficult to write and not easy to operate.

To summarize

First of all, don't take over completely, don't take over completely, don't take over completely, say the important things three times, then nothing can be done. Second, we can find that the custom Spring MVC configuration is a bit like an interceptor, that is, we can modify the request on the default basis. Some of the commonly used functions are still useful, so just know how to customize the extension.Of course, why a full take-over works also needs a simple understanding, so it's better to use a wrapped scene launcher, such as spring-boot-starter-web, to save us a lot of trouble.

Tags: Java Spring Spring Boot

Posted on Mon, 11 Oct 2021 12:45:02 -0400 by oddyseys