Spring Boot 学习(5)解决 WebMvcConfigurationSupport 静态资源失效问题

写在前面:最近利用晚上的时间在网上看视频学习Spring Boot,这博客是对学习的一点点总结及记录,技术是开源的、知识是共享的
如果你对Spring Boot 感兴趣,可以关注我的动态,我们一起学习。用知识改变命运,让家人过上更好的生活

自己踩到了一个很大的坑,这篇博客对这个大坑做一记录,希望对大家有所帮助。

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 以后还需要 重写它里面的方法。

扫描二维码关注公众号,回复: 8493523 查看本文章

然而问题又出来了,这样的继承会导致静态资源失效。

如何解决这个问题?

/**
 * 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来达到类似的功能
在这里插入图片描述

发布了73 篇原创文章 · 获赞 795 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/weixin_43570367/article/details/103651567