方法一:继承WebMvcConfigurerAdapter类
package com.imooc.demo.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class FileStaticConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { /** * /source/xxx 指文件的访问方式 如:localhost:8080/source/abc.wav * file:d/voice/ 指静态文件存放在服务器上的位置 */ registry.addResourceHandler("/source/**").addResourceLocations("file:"+"d:/voice/"); } }
方法二、
在SpringBoot2.0及Spring 5.0 WebMvcConfigurerAdapter已被废弃
官方推荐WebMvcConfigurer,代码如下:
package com.imooc.demo.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class FileStaticConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { /** * /source/xxx 指文件的访问方式 如:localhost:8080/source/abc.wav * file:d/voice/ 指静态文件存放在服务器上的位置 */ registry.addResourceHandler("/source/**").addResourceLocations("file:"+"d:/voice/"); } }