首先新建一个类,这个类属于适配器类型,放在配置相关的包下即可,或者放在拦截器过滤器一类的包下。
package com.hahaha.intercept;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class ResourcesConfigAdapter
extends WebMvcConfigurerAdapter {
@Value("${custom.server.download.dir}")
private String resourceDir;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/download/**").addResourceLocations("file:"+resourceDir);
super.addResourceHandlers(registry);
}
}
我们只需要在addResourceHandler
函数中传入需要匹配的路径,如上个例子中,我们写了/download/**
,假设我们的服务器的地址为127.0.0.1
端口为6666
,那么我们在访问127.0.0.1:6666/download/1.txt
或者127.0.0.1:6666/download/heiheihei/2.jpg
(诸如此类)的时候,就会被这个适配器发现,然后对应资源路径寻找对应名称的文件。资源路径是使用addResourceLocations
来进行配置的。这里,建议使用固定的路径,不用classpath
一类,因为放在不同容器中可能路径会不同。这里还用到了@Value
注解,这个注解的作用是加载配置文件中的属性。addResourceLocations
函数中传入的值是"file:D:/helloworld/download/"
当然了,对应到linux环境,你应该修改成这样的路径:file:/server/myapp/download
。祝大家编程愉快,没有bug。