标题
springboot2.0 获取相对路径文件夹下静态资源
场景
网站项目中有时候更换logo或者一些文本,在不用重新启动项目的情况下使用静态资源映射是一个比较好的办法
代码
1、放置静态资源
2、application.yml配置
config:
extPath: extPath
3、实现WebMvcConfigurer接口( WebMvcConfigurerAdapter 2.0已经弃用)
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
public static String StaticPath;
@Value("${config.extPath}")
public void setExtPath(String extPath) {
//static是我文件下创建的一个文件夹
StaticPath = extPath + System.getProperty("file.separator") + "static/";
}
@Bean
public SecurityInterceptor securityProperties() {
return new SecurityInterceptor();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//创建 显示
registry.addResourceHandler("/extStatic/**").addResourceLocations("file:" + StaticPath);
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
WebMvcConfigurer.super.addResourceHandlers(registry);
}
}
4、用法
-
浏览器
上面的在extPath/static 放置一个图片或者创建一个images文件夹放图片(本文在图一下创建了static/images目录)
在浏览器输入
http://127.0.0.1:8080/extStatic/images/xxxx.png
就可以看到效果 -
HTML
HTMl中也可以直接用 th:src="@{/extStatic/images/wx.png}"显示出来(thymeleaf)
总结
长路漫漫。。。