SpringBoot2.X 静态文件配置

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);
    }
}
posted @ 2019-09-26 16:36  xidianzxm  阅读(1496)  评论(0编辑  收藏  举报