在开发测试时,一般需要通过springboot访问静态资源(线上环境使用nginx高效访问静态资源)。
springboot默认的静态资源配置网上有很多资料,下面记一下springboot虚拟路径的配置方法。
需求说明:以/image/xxx.jpg访问位于D:/upload/中的图片
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
private final Logger logger = LoggerFactory.getLogger(WebConfigurer.class);
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//自定义的静态资源虚拟路径,可以定义多个,虚拟路径之间用'|'分割,路径内用'@'分割(格式自己定,只要能区分就行),本地路径D:/upload/必须以"/"结尾
String staticPathMapping = "/image/*@file:D:/upload/|/logo/*@file:D:/logo/";
logger.info("静态资源配置:{}", staticPathMapping);
if (staticPathMapping == null)
return;
String[] pattern = staticPathMapping.split("\\|");
for (String p : pattern) {
String[] item = p.split("@");
logger.info("注册静态资源配置: {} => {}", item[0], item[1]);
registry.addResourceHandler(item[0]).addResourceLocations(item[1]).setCacheControl(CacheControl.noCache());
}
}
}