springboot 2.x 里面访问静态资源的坑

在spring boot的自定义配置类继承 WebMvcConfigurationSupport 后,发现自动配置的静态资源路径(classpath:/META/resources/,classpath:/resources/,classpath:/static/,classpath:/public/)不生效。web

首先看一下 自动配置类的定义:spring

这是由于在 springboot的web自动配置类 WebMvcAutoConfiguration 上有条件注解 springboot

@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)

这个注解的意思是在项目类路径中 缺乏 WebMvcConfigurationSupport类型的bean时改自动配置类才会生效,因此继承 WebMvcConfigurationSupport 后须要本身再重写相应的方法。app

若是想要使用自动配置生效,又要按本身的须要重写某些方法,好比增长 viewController ,则能够本身的配置类能够继承  WebMvcConfigurerAdapter 这个类。不过在spring5.0版本后这个类被丢弃了 WebMvcConfigurerAdapter  ,虽然还能够用,可是看起来很差。ide

/**
 * 原来是这么写的:
 * public class BeanConfiguration extends WebMvcConfigurationSupport
 * 致使默认配置的静态资源不生效了
 */
@Configuration
public class BeanConfiguration implements WebMvcConfigurer {

    @Bean
    public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        mapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        mapper.setDefaultPropertyInclusion(JsonInclude.Include.ALWAYS);
        converter.setObjectMapper(mapper);
        return converter;
    }


    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //将咱们定义的时间格式转换器添加到转换器列表中,
        //这样jackson格式化时候但凡遇到Date类型就会转换成咱们定义的格式
        converters.add(jackson2HttpMessageConverter());

        // 添加字符串转换,否定若是返回字符串,则会报异常,其余converter 
        // 参考:org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport#addDefaultHttpMessageConverters
        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
        stringHttpMessageConverter.setWriteAcceptCharset(false);  // see SPR-7316
        converters.add(stringHttpMessageConverter);
    }

}
相关文章
相关标签/搜索