spring boot 静态文件本地路径配置

spring boot 静态文件本地路径配置…

应用场景

把文件独立出来放到其他盘符,比如我的服务在 E盘 文件放到 F盘
通常情况下放到对应项目的 webapps 下的文件才能正常访问,现在我需要访问F盘中的内容,这时候我就需要 自定义静态资源映射

方法一(代码实现)

实现类继承 WebMvcConfigurerAdapter 并重写方法 addResourceHandlers,代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.xt.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
* Created by TT on 2017-11-16.
*/

@Configuration
public class MyWebAppConfig extends WebMvcConfigurerAdapter {
/**
* addResourceHandler() 添加请求路径方法
* 注意:/video/** 改为 /**会覆盖默认的映射(classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/)
* 这种情况下项目路径下的resources目录中的所有文件都不能访问,
* 解决办法:addResourceLocations(String... resourceLocations) 依次把映射路径加入进去
* registry.addResourceHandler("/**").addResourceLocations("classpath:/resources/","classpath:/resources/","file:F:/迅雷下载/").;
* addResourceLocations() 添加映射路径方法
* 注意:必须要加 file:或classpath: 否则无法访问
* file:绝对路径下的映射
* classpath:相对路径下的映射
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//迅雷下载文件夹下有a.mp4,访问路径:http:xxxx/video/a.mp4
registry.addResourceHandler("/video/").addResourceLocations("file:F:/迅雷下载/");
super.addResourceHandlers(registry);
}
}

方法二(配置实现)

application.properties 配置文件

1
2
3
4
5
6
7
file.absolute.path = F:/迅雷下载/

#配置静态资源路径:多个资源以逗号分隔
#默认映射classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
#如果不用项目resource下的资源,可以不配置默认的
spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,\
classpath:/static/,classpath:/public/,file:${file.absolute.path}

参考链接: http://blog.csdn.net/catoop/article/details/50501706