web开发中,不可避免地是对静态资源的访问,Spring Boot默认的静态资源映射为三样:
- classpath:/META-INF/resources/
- classpath:/resources/
- classpath:/static/
- classpath:/public/
- / 项目的根路径
// 源码
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" };
也可以进行自定义静态资源映射,但是设置自定义后,系统默认的就会失效。所以优先系统默认。
自定义方法:
- 配置文件
- 编程
配置文件
spring:
mvc:
static-path-pattern: /backend/**
web:
resources:
static-locations:
- classpath:/backend/
将localhost:8080/backend/** 的访问
映射到 classpath:/backend/ 下
编程方式
@Slf4j
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
log.info("开启静态映射....");
registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");
registry.addResourceHandler("/front/**").addResourceLocations("classpath:/front/");
}
}
或者
@Slf4j
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");
registry.addResourceHandler("/front/**").addResourceLocations("classpath:/front/");
}
}
目前 WebMvcConfigurerAdapter 已废弃。可以使用实现WebMvcConfigurer接口,继续实现原有功能。
WebMvcConfigurationSupport 可以视为新版对WebMvcConfigurer的增强,二者在同一级目录之下。
标签:映射,静态,resources,classpath,static,registry,public,资源,backend From: https://www.cnblogs.com/serendipity-igao/p/16813429.html