我是靠谱客的博主 清新银耳汤,最近开发中收集的这篇文章主要介绍SpringBoot扩展SpringMVC的配置,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

  • 官方文档:Spring Boot Features

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这个注解会使默认配置失效的原因。

最后

以上就是清新银耳汤为你收集整理的SpringBoot扩展SpringMVC的配置的全部内容,希望文章能够帮你解决SpringBoot扩展SpringMVC的配置所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部