美文网首页
Spring-mvc之配置

Spring-mvc之配置

作者: AlanSun2 | 来源:发表于2019-06-21 09:35 被阅读0次

    Spring-mvc主要通过WebMvcConfigurationSupport类来实现对mvc的配置。
    它有一个子类DelegatingWebMvcConfiguration,类图如下:

    17F5845C-192D-4ef8-AC01-0C13C3E7BD8D.png

    1. 如何启用Spring-mvc配置呢?

    只要在某一个@Configuration类上加上@EnableWebMvc就可以了,如下:

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    
    /**
     * @author AlanSun
     * @date 2019/5/20 17:58
     **/
    @EnableWebMvc
    @Configuration
    public class MyConfig {
      ...
    }
    

    注意:整个项目中只要有一个@EnableWebMvc注解就可以了。多个也不会报错(已测试)

    2. 如何实现自定义的mvc配置呢?例如添加自定义转换器

    1. 想要实现mvc自定义配置其实也很简单,只要实现WebMvcConfigurer接口重写方法就可以,例如:
      添加自定义转换器,具体实现请参考Spring中自定义类型转换器实现-基于JavaConfig配置

    注意:你可以配置多个WebMvcConfigurer,Spring会整合这些所有的WebMvcConfigurer。具体过程请看1.1

    1.1 WebMvcConfigurer的工作流程

    这里必须要提到DelegatingWebMvcConfiguration类,看下源码(一部分):

    @Configuration
    public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
    
        private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
    
    
        @Autowired(required = false)
        public void setConfigurers(List<WebMvcConfigurer> configurers) {
            if (!CollectionUtils.isEmpty(configurers)) {
                this.configurers.addWebMvcConfigurers(configurers);
            }
        }
    
          ...other
    }
    

    首先可以看到DelegatingWebMvcConfiguration使用@Configuration注解,说明它是一个bean。setConfigurers方法使用@Autowired(required = false)注解,说明使用了依赖注入。最重要的来了,这里注入的依赖就是我们自定义的WebMvcConfigurer实现,该方法接收的是个LIst<WebMvcConfigurer>,说明我们可以自定义多个WebMvcConfigurer实现。最后LIst<WebMvcConfigurer>会被WebMvcConfigurerComposite接收。后续操作都由WebMvcConfigurerComposite来处理。

    1.2 WebMvcConfigurerComposite是什么

    WebMvcConfigurerComposite主要处理多个WebMvcConfigurer。看源码可以清楚的看到,WebMvcConfigurerComposite中的方法都是遍历WebMvcConfigurer列表来处理的。

    一般情况下实现WebMvcConfigurer都能满足开发需要,但是如果想要使用高级功能,可以使用第二种方法。

    1. 继承WebMvcConfigurationSupportDelegatingWebMvcConfiguration重写方法。

    SpringBoot中的mvc配置

    传送门

    相关文章

      网友评论

          本文标题:Spring-mvc之配置

          本文链接:https://www.haomeiwen.com/subject/ptflqctx.html