Spring Boot 静态资源无法访问的解决方案

spring boot 默认应自动托管 `static` 目录下的静态资源,但若出现 `no mapping for get /xxx.jpg` 警告,通常因 webmvc 配置被覆盖或自定义配置缺失导致;本文提供标准、可靠的手动注册方式以彻底解决该问题。

在 Spring Boot 应用中,静态资源(如图片、CSS、JS 文件)默认应存放在 src/main/resources/static/、src/main/resources/public/、src/main/resources/resources/ 或 src/main/resources/META-INF/resources/ 目录下,并通过 /** 路径自动对外提供服务。然而,当项目中存在自定义 @Configuration 类实现 WebMvcConfigurer(尤其是重写了 addResourceHandlers 方法但未显式调用父逻辑),或引入了某些第三方 Starter(如 Spring Security 未正确放行静态路径)、或使用了 spring.web.resources.add-mappings=false 等配置时,Spring Boot 的默认静态资源映射机制会被禁用,从而导致类似以下日志的 404 问题:

WARN  o.s.web.servlet.PageNotFound : No mapping for GET /2.jpg

此时,即使确认文件已正确放置在 src/main/resources/static/2.jpg,请求仍会失败。

✅ 正确解决方案是:显式注册标准静态资源位置。推荐创建一个轻量级配置类,实现 WebMvcConfigurer 并复用 Spring Boot 原生支持的 classpath 资源路径:

@Configuration
public class StaticResourceConfiguration implements WebMvcConfigurer {

    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
        "classpath:/META-INF/resources/",
        "classpath:/resources/",
        "classpath:/static/",
        "classpath:/public/"
    };

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS)
                .setCachePeriod(3600) // 可选:设置 1 小时缓存(单位:秒)
                .resourceChain(true); // 启用资源链(支持版本号、gzip 等)
    }
}

? 注意事项:

  • ✅ 该配置兼容 Spring Boot 2.x 与 3.x(3.x

    中 WebMvcConfigurer 仍有效,但需确保未启用 @EnableWebMvc —— 否则将完全关闭 Spring Boot 自动配置);
  • ❌ 切勿在配置类上添加 @EnableWebMvc,否则将覆盖全部默认 MVC 配置(包括静态资源、消息转换器、视图解析器等);
  • ✅ 若使用 Spring Security,请确保静态资源路径被放行,例如:
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(authz -> authz
            .requestMatchers("/css/**", "/js/**", "/images/**", "/**/*.jpg", "/**/*.png").permitAll()
            .anyRequest().authenticated()
        );
        return http.build();
    }
  • ✅ 检查 application.properties 中是否误设了 spring.web.resources.add-mappings=false —— 如有,请删除或设为 true(默认即为 true)。

最后,重启应用并直接访问 http://localhost:8080/2.jpg 即可验证资源是否正常加载。该方案简洁、可维护,且与 Spring Boot 设计理念一致,是生产环境推荐的标准实践。