008 WEBmvc的自动配置

一 .概述

  在springboot之中开发一个web项目是十分的简单的,我们本节就看一下springboot之中mvc的自动配置原理,这样可以帮助我们在后面覆盖springboot的默认的配置信息.


二 .springboot的mvc自动配置

 下面就是springboot的webMVC的自动配置类,我们首先分析一下主要的结构问题. 

@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,
        WebMvcConfigurerAdapter.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
        ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {

[1]是一个配置类

[2]需要在web环境下生效

[3]在类路径下需要有Servlet.class,DispatcherServlet.class,WebMvcConfigurerAdapter.class

[4]在容器之中没有WebMvcConfigurationSupport的bean

[5]本类是在DispatcherServletAutoConfiguration和ValidationAutoConfiguration自动配置之后进行的.

    @Bean
    @ConditionalOnMissingBean(HiddenHttpMethodFilter.class)
    public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
        return new OrderedHiddenHttpMethodFilter();
    }

首先,我们看到,springboot为我们提哦给你了一个Rest过滤器,这个比较简单.

  @Configuration
    @Import(EnableWebMvcConfiguration.class)
    @EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
    public static class WebMvcAutoConfigurationAdapter extends WebMvcConfigurerAdapter {

这个就是mvc部分的核心配置了.

首先我们发现就是给我们添加了一个EnableWebMvcConfiguration配置类,然后帮助我们映射了WebMvcProperties和ResourceProperties的属性配置对象.

通过这里,我们就知道了mvc的配置主要集中在WebMvcProperties这个属性的配置之中.

下面我们看看具体的配置: 

@Bean
        @ConditionalOnMissingBean
        public InternalResourceViewResolver defaultViewResolver() {
            InternalResourceViewResolver resolver = new InternalResourceViewResolver();
            resolver.setPrefix(this.mvcProperties.getView().getPrefix());
            resolver.setSuffix(this.mvcProperties.getView().getSuffix());
            return resolver;
        }

        @Bean
        @ConditionalOnBean(View.class)
        @ConditionalOnMissingBean
        public BeanNameViewResolver beanNameViewResolver() {
            BeanNameViewResolver resolver = new BeanNameViewResolver();
            resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
            return resolver;
        }

        @Bean
        @ConditionalOnBean(ViewResolver.class)
        @ConditionalOnMissingBean(name = "viewResolver", value = ContentNegotiatingViewResolver.class)
        public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) {
            ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
            resolver.setContentNegotiationManager(
                    beanFactory.getBean(ContentNegotiationManager.class));
            // ContentNegotiatingViewResolver uses all the other view resolvers to locate
            // a view so it should have a high precedence
            resolver.setOrder(Ordered.HIGHEST_PRECEDENCE);
            return resolver;
        }

在上面,我们可以看到springboot为我们提供了三个视图解析器.

@Bean
        @ConditionalOnProperty(prefix = "spring.mvc", name = "date-format")
        public Formatter<Date> dateFormatter() {
            return new DateFormatter(this.mvcProperties.getDateFormat());
        }

为我们提供了一个日期格式化的格式化器,可以通过spring.mvc.data-formar进行配置.

@Bean
        public WelcomePageHandlerMapping welcomePageHandlerMapping(
                ResourceProperties resourceProperties) {
            return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(),
                    this.mvcProperties.getStaticPathPattern());
        }

为我们配置了一个欢迎页的处理器映射器.我们发现就是默认的index.html页面.

@Configuration
        @ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
        public static class FaviconConfiguration {

为我们提供了一个/favicon.ico的网站图标的映射.

等等,这些都是springboot为我们提供的.

我们最终发现实际上就是帮助我们配置了一个WebMvcConfigurer的bean.


三 .WebMvcConfigurer的作用

  在springboot之中,使用了WebMvcConfigurer帮助我们覆盖我们的默认配置.

  我们可以向容器之中添加一个WebMvcConfigurer组件,这样springboot会将默认的配置和我们的配置进行组合,然后成为springboot最终的配置.

  由于WebMvcConfigurer是一个接口,因此我们常常添加的是一个WebMvcConfigurer的适配器类WebMvcConfigurerAdapter.

public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {
  
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    }
  // 配置异步支持
    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
    }

  // 配置默认的路径映射
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    }

   // 可以添加一些formatter
    @Override
    public void addFormatters(FormatterRegistry registry) {
    }

  //可以添加一些拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    }
  // 可以添加一些资源处理器
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    }

   //可以添加一些跨域映射
    @Override
    public void addCorsMappings(CorsRegistry registry) {
    }

   // 添加视图控制器
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    }
    //配置视图解析器
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
    }  
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
    }  
    @Override
    public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) {
    }

   //添加消息转换器
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    }

  
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    }
 
    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
    }
  //添加异常处理器
    @Override
    public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
    }
   //添加校验器
    @Override
    public Validator getValidator() {
        return null;
    }
    @Override
    public MessageCodesResolver getMessageCodesResolver() {
        return null;
    }

}

四 .mvc的自定义配置

  [1]现在我们知道了mvc的自定义的配置方法,就是向容器之中加入一个bean,然后springboot在配置的时候就会加入我们的配置.

  [2]使用WebMvcConfigurer来统一的进行配置.

原文地址:https://www.cnblogs.com/trekxu/p/9739727.html