这里写目录标题
一、系统默认静态资源路径
默认情况下,Spring Boot会从以下位置自动 serve 静态资源:
- classpath:/static
- classpath:/public
- classpath:/resources
- classpath:/META-INF/resources
只要将静态资源放在这些默认目录下,Spring Boot应用就能直接访问它们。
二、静态资源不在默认目录,需要配置
当静态资源没放在这些默认目录下,Spring Boot应用就不能直接访问它们。可以通过配置类或者application.yml/application.properties文件来实现。
1.方法一:通过配置类设置(java代码实现)
创建WebConfig类(类名随意,最好见名知意),实现WebMvcConfigurer接口,并在WebConfig类中提供WebMvcConfigurer接口中addResourceHandlers方法的具体实现
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/custom/**")
.addResourceLocations("classpath:/custom-folder/")
.addResourceLocations("file:/absolute/path/to/your/resources/");
}
}
addResourceHandler方法指定了请求的URL(例如/custom/**)
而addResourceLocations则指定了这些请求应该映射到的静态资源路径
2.方法二:application.yml 配置
spring:
resources:
static-locations:
- classpath:/custom-folder/
- classpath:/static/
- file:/absolute/path/to/your/resources/
3.方法三:application.properties 配置
spring.resources.static-locations=classpath:/custom-folder/,classpath:/static/,file:/absolute/path/to/your/resources/
标签:SpringBoot,映射,静态,classpath,默认,custom,application,resources
From: https://blog.csdn.net/qq_65455837/article/details/139163720