一、确保为web项目,创建WebConfig 实现WebMvcConfigurer (推荐)或 继承WebMvcConfigurationSupport
说明:
SpringBoot2.0 配置WebMvc 需 原因:继承WebMvcConfigurationSupport可能会导致其他库的Mvc配置失效,如:在自定义一个类extends WebMvcConfigurationSupport
或implements WebMvcConfigurer
Spring Boot中只能有一个WebMvcConfigurationSupport配置类是真正起作用的,对于这个问题,其实可以通过implements WebMvcConfigurer
来解决,多个不同的配置类实现这个接口后的配置都可以正常运行。推荐使用implements WebMvcConfigurer
extends WebMvcConfigurationSupport
后会导致Swagger2
库的资源无法访问
二、覆写addResourceHandlers方法
通过相对路径访问(访问resource中的资源)的配置类
下面的代码会将拦截所有/static/**
,并返回 SpringBoot resource目录下所对应的资源
registry.addResourceHandler("/static/**")
.addResourceLocations(“classpath:/static/”);
完整示例:
@Configurationpublic class WebConfig implements WebMvcConfigurer{@AutowiredImageConfig imageConfig;@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");}}
通过绝对路径访问的配置类
下面的代码会将拦截所有/image/**
,并返回 filePath路径所对应的资源,filePath
为文件的绝对路径,如:D:\test\test.png
registry.addResourceHandler("/image/**").addResourceLocations(“file:” + filePath);
完整示例:
@Configurationpublic class WebConfig implements WebMvcConfigurer{@AutowiredImageConfig imageConfig;@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {//配置图片静态资源处理器registry.addResourceHandler("/images/**").addResourceLocations("file:" + imageConfig.getSavePath());}}
注意
继承WebMvcConfigurationSupport可能会导致其他库的Mvc配置失效,如:在自定义一个类extends WebMvcConfigurationSupport
后会导致Swagger2
库的资源无法访问linux 路径分隔符为/
,windows为\
通过yml配置文件设置资源访问路径时,必须在路径最后加上分隔符错误实例:D:\classdesign-photo\images
正确实例:D:\classdesign-photo\images\
yml配置示例:
storage:image:#保存路径save-path: D:\classdesign-photo\images\#允许上传的类型allow-type:- jpg- png