Spring Boot 默認會挨個從
META/resources > resources > static > public 里面找是否存在相應的資源,如果有則直接返回。
默認配置:
spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
建議將靜態資源和代碼分離,將靜態資源文件存儲在CDN
application.properties
spring.resources.static-locations=classpath:/templates/,classpath:/static/,classpath:/public/
addResourceHandler方法是設置訪問路徑前綴,addResourceLocations方法設置資源路徑,如果你想指定外部的目錄也很簡單,直接addResourceLocations指定即可,代碼如下:
String outside_static = "/opt/app/outside_static";
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/templates/")
.addResourceLocations("classpath:/static/")
.addResourceLocations("classpath:/public/")
.addResourceLocations("file:" + outside_static);
@Configuration
public class StaticFilePathConfig implements WebMvcConfigurer {////implements WebMvcConfigurer //extends WebMvcConfigurationSupport
// @Value("${file.staticAccessPath}")
// private String staticAccessPath;
// @Value("${file.uploadFolder}")
// private String uploadFolder;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//staticAccessPath:/static/**
//"file:" + uploadFolder:/media/peter/Data/dev/bisonSpace/bison-web-service/bison-service-product/target/static/
//如果是Windows環境的話 file:=改為=》file:///
// registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + uploadFolder);
File path = null;
try {
path = new File(ResourceUtils.getURL("classpath:").getPath());
//file:/data/github/testmanagement/target/testmanagement-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!
System.out.println(path.getPath());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//server.tomcat.basedir=outsidefile/jacococoverage
String outside_templates=path.getParentFile().getParentFile().getParent()+File.separator;
outside_templates=outside_templates.substring(5,outside_templates.length());
//String outside_static=path.getParentFile().getParentFile().getParent()+File.separator+"outsidefile"+File.separator+"jacococoverage"+File.separator;
System.out.println(outside_static);
//file:/data/github/testmanagement/target/
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/templates/")
.addResourceLocations("classpath:/static/")
.addResourceLocations("classpath:/public/")
.addResourceLocations("file:" + outside_static);
// super.addResourceHandlers(registry);
}
}
