1.addResourceHandler
新增 自定义的静态资源路径映射
addResourceHandler
默认是在原有静态资源处理规则的基础上 新增 自定义的静态资源路径映射。也就是说,它不会直接覆盖 Spring Boot 的默认静态资源处理逻辑(如 /static/
、/public/
等路径),而是通过添加新的规则来扩展功能。
registry.addResourceHandler("/custom/**")
.addResourceLocations("classpath:/custom/");
2.错误案例
registry.addResourceHandler("/**") // 路径匹配所有请求
.addResourceLocations("classpath:/"); // 映射到类路径根目录
/**
是一个通配符路径,表示所有请求(包括/
、/favicon.ico
、/index.html
等)都会被这条规则处理。classpath:/
是类路径根目录,即src/main/resources/
下的文件。- 默认静态资源路径被覆盖:
- Spring Boot 默认会从
/static/
、/public/
等目录加载静态资源(如src/main/resources/static/index.html
)。 - 该配置强制所有请求直接从类路径根目录查找,导致:
- 访问
/index.html
时,Spring Boot 会尝试从classpath:/index.html
(而非classpath:/static/index.html
)加载,如果文件不存在则返回 404。 favicon.ico
如果放在类路径根目录(如src/main/resources/favicon.ico
),则能被正确找到。
- 访问
- Spring Boot 默认会从