写在前面: 我是「扬帆向海」,这个昵称来源于我的名字以及女朋友的名字。我热爱技术、热爱开源、热爱编程。
技术是开源的、知识是共享的。
这博客是对自己学习的一点点总结及记录,如果您对 Java、算法 感兴趣,可以关注我的动态,我们一起学习。
用知识改变命运,让我们的家人过上更好的生活
。
相关文章:
自己踩到了一个很大的坑,这篇博客对这个大坑做一记录,希望对大家有所帮助。
WebMvcConfigurationAdapter 在spring boot 2.0被废弃以后,可以使用系提供的类:WebMvcConfigurationSupport,来替换之前的WebMvcConfigurationAdapter 。 但是替换之后之前的静态资源文件 会被拦截,导致无法可用。
一、 问题分析
从上图可以看出,WebMvcConfigurationAdapter 在spring boot 2.0被废弃了。
当选择继承WebMvcConfigurationSupport 以后,发现自动配置的静态资源失效了。
先看源码
@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 {
public static final String DEFAULT_PREFIX = "";
public static final String DEFAULT_SUFFIX = "";
private static final String[] SERVLET_LOCATIONS = { "/" };
@Bean
@ConditionalOnMissingBean(HiddenHttpMethodFilter.class)
@ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled", matchIfMissing = false)
public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
return new OrderedHiddenHttpMethodFilter();
}
从源码看出容器中有@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)这个注解。
当容器中没有这个组件的时候,这个自动配置类才生效
因此当选择继承 WebMvcConfigurationSupport 以后还需要 重写它里面的方法。
然而问题又出来了,这样的继承会导致静态资源失效。
如何解决这个问题?
/**
* An implementation of {@link WebMvcConfigurer} with empty methods allowing
* subclasses to override only the methods they're interested in.
*
* @author Rossen Stoyanchev
* @since 3.1
* @deprecated as of 5.0 {@link WebMvcConfigurer} has default methods (made
* possible by a Java 8 baseline) and can be implemented directly without the
* need for this adapter
*/
@Deprecated
public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {
deprecated as of 5.0 {@link WebMvcConfigurer} has default methods (made
possible by a Java 8 baseline) and can be implemented directly without the
这句话大概的意思是,从Spring 5.0 开始,使用java 8 有默认的方法可以直接实现不需要适配器。
从Springboot 2.x开始,由于 WebMvcConfigure接口包含了WebMvcConfigurerAdapter 类中所有方法的默认实现,因此WebMvcConfigurerAdapter 这个适配器就被弃用了。
二、 解决 WebMvcConfigurationSupport 静态资源失效问题的办法
WebMvcConfigurerAdapter自从Spring5.0版本开始已经不建议使用了,但是你可以实现WebMvcConfigurer来达到类似的功能。
由于水平有限,本博客难免有不足,恳请各位大佬不吝赐教!