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

写在前面: 我是「扬帆向海」,这个昵称来源于我的名字以及女朋友的名字。我热爱技术、热爱开源、热爱编程。技术是开源的、知识是共享的。

这博客是对自己学习的一点点总结及记录,如果您对 Java算法 感兴趣,可以关注我的动态,我们一起学习。

用知识改变命运,让我们的家人过上更好的生活

相关文章:

Springboot 系列文章


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

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


由于水平有限,本博客难免有不足,恳请各位大佬不吝赐教!

  • 15
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 12
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值