SpringBoot扩展SpringMVC的配置

If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.

即如果要扩展,就加一个配置类,用@Configuration标注,同时实现WebMvcConfigurer这个接口,要注意的一点是,如果用了@EnableWebMvc这个注解,就表示会全权接管mvc的配置,默认配置全部失效

//扩展mvc配置
@Configuration
//@EnableWebMvc // 加了这个注解就会全权接管mvc配置,默认配置失效
public class MyConfig implements WebMvcConfigurer {

    /** 扩展视图控制 **/
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //把/te请求重定向到index.html
        registry.addRedirectViewController("/te", "/index");
    }

    /** 扩展视图解析器 **/
    @Bean
    public ViewResolver getMyViewResolver() {
        return new MyViewResolver();
    }

    public static class MyViewResolver implements ViewResolver {
        @Override
        public View resolveViewName(String viewName, Locale locale) throws Exception {
            return null;
        }
    }
}
  • 分析一下

@EnableWebMvc这个注解里,主要是引入了"DelegatingWebMvcConfiguration"这个类。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {}

DelegatingWebMvcConfiguration这个类里,会自动注入所有的WebMvcConfigurer,同时,他还继承了WebMvcConfigurationSupport。

@Autowired(required = false)
public void setConfigurers(List<WebMvcConfigurer> configurers) {
   if (!CollectionUtils.isEmpty(configurers)) {
      this.configurers.addWebMvcConfigurers(configurers);
   }
}

与此同时,我们回过头看看webmvc的自动配置类:WebMvcAutoConfiguration

@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
      ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
	//...
}

@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)

如果存在WebMvcConfigurationSupport这个类(@EnableWebMvc引入的那个类的父类就是这个),这个自动配置类就失效,这也就是@EnableWebMvc这个注解会使默认配置失效的原因。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值