Spring运行时新增静态文件无需重启服务的实现方案咨询
解决方案
你可以通过修改Spring资源配置直接实现需求,无需新增Controller,具体方案如下:
前提注意
如果你的应用是打包成JAR包运行,classpath路径下的static目录是封装在JAR包内的,运行时无法直接往JAR包内写入新文件。建议同时配置本地文件系统目录作为静态资源存放路径,运行时新增的文件直接存放到该本地目录即可。
配置方式
1. 配置文件方式(无需写Java代码,推荐Spring Boot场景使用)
直接在application.properties中添加如下配置即可:
# 关闭静态资源缓存 spring.web.resources.cache.period=0 spring.web.resources.chain.cache=false # 配置静态资源路径,可同时保留classpath默认路径和本地文件系统路径 # 请将file:后面的路径替换为你实际要使用的本地静态资源存放目录 spring.web.resources.static-locations=classpath:/static/,file:/opt/app/static-resources/
如果使用application.yml,对应配置如下:
spring: web: resources: cache: period: 0 chain: cache: false static-locations: - classpath:/static/ - file:/opt/app/static-resources/
2. Java代码配置方式(适用于原生Spring MVC场景)
新增配置类实现WebMvcConfigurer接口,重写静态资源映射规则即可:
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 StaticResourceConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**") // 可自定义多个资源路径 .addResourceLocations("classpath:/static/", "file:/opt/app/static-resources/") // 关闭缓存 .setCachePeriod(0) .resourceChain(false); } }
额外说明
如果是本地开发环境,使用IDE直接运行项目时,需要开启IDE的自动编译功能,新增/修改src/main/resources/static下的文件后,IDE会自动同步到编译后的classpath目录,无需重启应用即可直接访问。
上述方案完全关闭了静态资源的服务端缓存,每次请求都会重新扫描对应资源路径下的文件,新增文件可以立即生效,不需要重启服务。
内容的提问来源于stack exchange,提问作者v-moe
相关产品推荐
相关产品推荐

