You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 2.x中如何禁用静态内容处理适配自定义拦截器?

解决方案

一、排查类库配置是否干扰Spring Boot自动配置

先检查类库中注册拦截器的@Configuration类是否添加了@EnableWebMvc注解。如果存在这个注解,会完全禁用Spring Boot的Web自动配置,包括控制器@RequestMapping映射的自动扫描逻辑。这就是你设置spring.web.resources.add-mappings=false后,控制器端点也无法被识别、出现No mapping for GET /about错误的核心原因。

如果类库确实使用了@EnableWebMvc,建议移除它,改用WebMvcConfigurer接口扩展配置(无需添加@EnableWebMvc),这样Spring Boot的自动配置会保留,控制器映射和静态资源配置都能正常工作。

二、正确禁用静态资源映射

确认类库没有干扰自动配置后,你可以通过自定义WebMvcConfigurer完全禁用静态资源处理,同时保留控制器映射:

@Configuration
public class StaticResourceDisableConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 将所有静态资源请求映射到不存在的路径,使其无法被处理
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/non-existent-resources/");
    }
}

或者,你也可以直接在启动类中排除静态资源自动配置类:

@SpringBootApplication(exclude = {ResourceAutoConfiguration.class})
public class YourRestApiApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourRestApiApplication.class, args);
    }
}

三、更健壮的拦截器兼容方案

考虑到你的类库需要供多个应用引入,建议修改拦截器逻辑,兼容非HandlerMethod类型的handler,而非依赖禁用静态资源。这样即使其他应用有静态资源需求,你的类库也能正常运行:

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    // 仅处理控制器方法类型的handler,其他类型直接放行
    if (!(handler instanceof HandlerMethod)) {
        return true;
    }

    final HandlerMethod method = (HandlerMethod) handler;
    SomeAnnotation annotation = method.getAnnotation(SomeAnnotation.class);
    // 执行你的注解检查逻辑
    // ...

    return true;
}

这种方案既解决了当前报错问题,也提升了类库的兼容性与健壮性。

内容的提问来源于stack exchange,提问作者Daniel Kesner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 11:33:12