spring boot扩展spring mvc原理分析

我们都知道spring boot自动配置了各种场景所需要的组件,包括web模块,
虽然帮我们导入了许多组件,但这些配置在实际开发中满足不了我们的需要,因此我们需要在自动配置的基础上进一步扩展spring mvc

  • 截取自Spring Boot官方文档

If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration (interceptors, formatters, view controllers etc.) you can add your own @Configuration class of type WebMvcConfigurerAdapter, but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter or ExceptionHandlerExceptionResolver you can declare a WebMvcRegistrationsAdapter instance providing such components.
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.

1.扩展

根据官方文档的定义,如果我们想要扩展MVC,只需要自己编写一个配置类,并且这个类是属于WebMvcConfigurerAdapter,并且不能被@EnableWebMvc标注,在spring boot2.0.0及以上,可以不用继承WebMvcConfigurerAdapter,只需要实现WebMvcConfigurer接口,选择方法进行重写即可,下面是一个案例

//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
       // super.addViewControllers(registry);
        //浏览器发送 /test请求来到 success
        registry.addViewController("/test").setViewName("success");
    }
}

这样就注册了一个视图映射器,既保留了所有的自动配置,也能用我们扩展的配置

2.原理

  • org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration中,WebMvcAutoConfiguration是SpringMVC的自动配置类
  • 在做其他自动配置时会导入;@Import({WebMvcAutoConfiguration.EnableWebMvcConfiguration.class})
 	@Configuration(
        proxyBeanMethods = false
    )
    @Import({WebMvcAutoConfiguration.EnableWebMvcConfiguration.class})
    @EnableConfigurationProperties({WebMvcProperties.class, ResourceProperties.class})
    @Order(0)
    public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {

我们看一下EnableWebMvcConfiguration.class
在这里插入图片描述

  • 容器中所有的WebMvcConfigurer都会一起起作用
  • 我们的类也会起作用

​ 效果:SpringMVC的自动配置和我们的扩展配置都会起作用;

发布了37 篇原创文章 · 获赞 11 · 访问量 3881

猜你喜欢

转载自blog.csdn.net/Alphr/article/details/105013337