springboot关于webmvc配置问题记录

在以前的文章(springboot配置静态资源访问路径)中说过,springboot默认的加载静态资源的地方是在resources目录下的static文件夹下,其实除了resources目录下得static文件夹能够被访问,在resources目录下建立resources文件夹、public文件夹、META-INF/resources文件夹都是能够被访问到的,只不过springboot默认推荐咱们使用static文件夹,并且查找的优先级是META-INF/resources》public》resources》static。html

当咱们要修改springboot默认的静态资源加载路径的时候,咱们能够直接在配置文件properties、yml中直接设置,或者找个配置类(使用@configuration注解的类)使其继承org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter或者org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport并重写addResourceHandlers(ResourceHandlerRegistry registry)方法,这个方法在WebMvcConfigurerAdapter和WebMvcConfigurationSupport中都是空实现。web

在此,建议在springboot 1.x版本使用WebMvcConfigurerAdapter这个类,2.x版本实现WebMvcConfigurer 接口,不推荐使用WebMvcConfigurationSupport和@EnableWebMvc注解。由于springboot默认会给咱们添加一个配置类WebMvcAutoConfiguration,可是这个配置类的加载是有条件的( @ConditionalOnMissingBean(WebMvcConfigurationSupport.class)),只有缺乏WebMvcConfigurationSupport配置类才会生效,当咱们使用继承WebMvcConfigurationSupport或者@EnableWebMvc注解(这个注解会导入DelegatingWebMvcConfiguration,这个类继承自WebMvcConfigurationSupportspring

)时,springboot的就不会帮咱们加载WebMvcAutoConfiguration这个配置类了,这个时候就须要咱们进行一些webmvc的配置。并且比较坑的是若是咱们使用继承WebMvcConfigurationSupport这种方式,不能屡次使用,也就是说若是咱们有两个及以上配置类继承WebMvcConfigurationSupport时,只会有一个生效;当咱们即便用@EnableWebMvc又有配置类继承WebMvcConfigurationSupport时,咱们的配置类是会生效的。springboot

@EnableWebMvc、WebMvcConfigurationSupport、WebMvcConfigurerAdapter这三个使用效果:mvc

  1. 使用WebMvcConfigurerAdapter  =====》所有生效
  2. 使用WebMvcConfigurationSupport(多个)   ====》某一个生效,其余不生效
  3. 使用WebMvcConfigurerAdapter + WebMvcConfigurationSupport       ====》WebMvcConfigurationSupport生效
  4. 使用@EnableWebMvc+ WebMvcConfigurationSupport       ====》WebMvcConfigurationSupport生效
  5. 使用@EnableWebMvc+ WebMvcConfigurerAdapter     ====》WebMvcConfigurerAdapter 不生效
相关文章
相关标签/搜索