SpringMVC 静态资源访问不到的问题

本文探讨了在SpringMVC中遇到静态资源无法访问的问题,原因是继承了WebMvcConfigurationSupport并启用了@EnableWebMvc,导致自定义的资源处理配置失效。解决方案是取消@EnableWebMvc注解,或者选择直接继承WebMvcConfigurationSupport或DelegatingWebMvcConfiguration。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现象:

如下配置静态资源拦截,运行时,访问不到static 目录下的静态资源。

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    System.out.println("addResourceHandlers=======");
    registry.addResourceHandler("/static/**")
            .addResourceLocations("/static/");
}

原因:

@EnableWebMvc
class WebConfig extends WebMvcConfigurationSupport

继承了  WebMvcConfigurationSupport 类,导致 addResourceHandlers 方法的配置完全没有起作用。

因为@EnableWebMvc 会自动导入DelegatingWebMvcConfiguration,会重写addResourceHandlers() 方法。

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {}

@EnableWebMvc 的源码

 

* <p><strong>Note:</strong> only one {@code @Configuration} class may have the
* {@code @EnableWebMvc} annotation to import the Spring Web MVC
* configuration. There can however be multiple {@code @Configuration} classes
* implementing {@code WebMvcConfigurer} in order to customize the provided
* configuration.
只有一个类可以加@EnableWebMvc注解,导入spring web mvc 的配置。但是可以由多个类实现接口WebMvcConfigurer 去提供自定义配置。

*
* <p>If {@link WebMvcConfigurer} does not expose some more advanced setting that
* needs to be configured consider removing the {@code @EnableWebMvc}
* annotation and extending directly from {@link WebMvcConfigurationSupport}
* or {@link DelegatingWebMvcConfiguration}, e.g.:

如果WebMvcConfigurer没有暴露任何配置,可以考虑去掉@EnableWebMvc,直接继承WebMvcConfigurationSupport或DelegatingWebMvcConfiguration。

@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值