You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Boot 3.1.5中访问根目录下的version.html文件

Spring Boot 3.1.5 根路径托管version.html的解决办法

办法1:自定义静态资源映射配置

写个配置类,扩展Spring Boot的静态资源处理逻辑,直接映射根目录下的version.html:

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("/version.html")
                .addResourceLocations("file:./version.html");
    }
}
  • file:./version.html指向应用运行目录下的目标文件,完全适配运维手动注入的路径。
  • 要是应用打包成jar运行,确保version.html和jar包放在同一目录就行。

办法2:修改静态资源位置配置

直接在配置文件里把应用根目录加入静态资源扫描列表:

application.properties

spring.web.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:./

application.yaml

spring:
  web:
    resources:
      static-locations:
        - classpath:/META-INF/resources/
        - classpath:/resources/
        - classpath:/static/
        - classpath:/public/
        - file:./
  • 加了file:./之后,Spring Boot会自动扫描应用运行目录下的静态文件,自然就能访问到version.html。
  • 注意:这种方式会让根目录下所有符合静态资源规则的文件都对外可访问,如果根目录有敏感文件,得额外做过滤。

办法3:写个简单控制器映射

如果上面两种方式不合适,就写个控制器直接返回文件内容:

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class VersionController {
    @GetMapping(value = "/version.html", produces = MediaType.TEXT_HTML_VALUE)
    public FileSystemResource getVersionHtml() {
        return new FileSystemResource("./version.html");
    }
}
  • 收到/version.html请求时,这个控制器会直接读取根目录下的文件并返回。
  • 如果是容器部署,可根据实际情况修改文件路径,或者通过环境变量注入路径。

内容的提问来源于stack exchange,提问作者franzcatch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 14:36:05