目录结构如上图所示。
方法一:设置application.yml
在spring下增加:
spring:
profiles:
save-path: f:/upload/
resources:
static-locations: file:f:/upload/
mvc:
static-path-pattern: /res/**
现在可以访问url:/res/*,达到访问f:/upload/的文件和文件夹,但是原来的默认的静态文件夹无法访问了。
方法二:
解决办法:如下面的代码,请自行配置,不做解说。
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfg implements WebMvcConfigurer {
@Value("${spring.profiles.save-path}")
private String configSavePath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/res/**").addResourceLocations("file:"+configSavePath);
}
}
运行可以发现,既可以访问默认的文件夹 classpath:/static,classpath:/public,classpath:/resources,classpath:/META-INF/resources.也可以访问自定义的静态文件夹。
下面的代码在spring 5中是过时的,在idea中有删除线提示,影响代码的美观。
@Configuration
public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/my/**").addResourceLocations("classpath:/my/");
super.addResourceHandlers(registry);
}
}