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

Spring Boot如何根据profile配置动态替换静态页面redoc的spec-url属性值

Spring Boot动态配置Redoc的spec-url属性实现方案

方案1:使用Thymeleaf模板引擎(运行时动态适配profile,最灵活)

这是最符合Spring Boot生态的实现方式,不需要改太多原有代码:

  • 第一步:引入Thymeleaf starter依赖,Maven配置示例:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  • 第二步:将原放在resources/static下的静态html文件移动到resources/templates目录下。
  • 第三步:在对应profile的配置文件(application-dev.yml、application-prod.yml等)中添加自定义配置:
# dev环境配置示例
custom:
  redoc:
    spec-url: http://localhost:8080/v2/api-docs
# prod环境配置示例
custom:
  redoc:
    spec-url: https://你的线上域名/v2/api-docs
  • 第四步:修改html中的redoc标签,使用Thymeleaf属性注入配置值:
<redoc th:attr="spec-url=${@environment.getProperty('custom.redoc.spec-url')}"></redoc>
  • 第五步:新增一个简单的Controller接口,返回模板视图:
@Controller
public class DocController {
    @GetMapping("/doc")
    public String redocPage() {
        // 返回templates目录下的html文件名,不用加后缀
        return "你的redoc页面文件名";
    }
}

启动项目时指定对应profile,访问/doc接口就能看到对应环境的spec-url自动生效。

方案2:纯静态页+JS动态赋值(不需要引入模板引擎)

如果不想改动原有静态资源架构,可以用前端动态赋值的方式实现:

  • 第一步:和方案1一样在各profile配置文件中添加custom.redoc.spec-url配置。
  • 第二步:新增一个返回配置值的接口:
@RestController
@RequestMapping("/config")
public class ConfigController {
    @Value("${custom.redoc.spec-url}")
    private String specUrl;

    @GetMapping("/redoc-url")
    public String getSpecUrl() {
        return specUrl;
    }
}
  • 第三步:修改静态html,新增JS逻辑动态设置spec-url属性:
<!-- 先把redoc标签的spec-url属性留空 -->
<redoc id="redoc"></redoc>
<script>
window.onload = async function() {
    // 调用接口获取对应环境的地址
    const specUrl = await fetch('/config/redoc-url').then(res => res.text());
    document.getElementById('redoc').setAttribute('spec-url', specUrl);
}
</script>

方案3:打包时替换占位符(仅适合打包时固定环境的场景)

如果你的不同环境是分开打包的,可以用Maven资源过滤功能直接替换静态页中的占位符:

  • 第一步:在pom.xml中开启静态资源过滤,配置不同profile对应的url值:
<build>
    <resources>
        <resource>
            <directory>src/main/resources/static</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
    <profiles>
        <profile>
            <id>dev</id>
            <properties>
                <spec.url>http://localhost:8080/v2/api-docs</spec.url>
            </properties>
        </profile>
        <profile>
            <id>prod</id>
            <properties>
                <spec.url>https://你的线上域名/v2/api-docs</spec.url>
            </properties>
        </profile>
    </profiles>
</build>
  • 第二步:静态页中的redoc标签直接写占位符即可:
<redoc spec-url='${spec.url}'></redoc>

打包时指定对应profile,比如mvn package -Pprod,打包完成后静态页中的占位符会自动替换为对应环境的地址。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:06:01