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

如何在Spring Boot Thymeleaf中根据环境读取application.yaml的图片链接

在Spring Boot Thymeleaf中根据环境自动加载对应图片链接

我有生产和开发两个环境,不同环境下图片链接不同,当前配置文件如下:

生产环境配置(application.yaml)

image:
  url: prod-env-link

开发环境配置(application-dev.yaml)

image:
  url: prod-env-link

现有Thymeleaf页面代码:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Some title</title>
</head>
<body>
    <img th:src="image-link" />
</body>
</html>

请问如何在页面中根据当前环境自动获取对应的图片链接?


解决方案

方法一:直接通过Thymeleaf表达式读取配置

Spring Boot会自动加载当前激活环境的配置文件,你可以直接在Thymeleaf模板中用环境变量表达式读取配置项:

修改页面中的img标签:

<img th:src="${@environment.getProperty('image.url')}" />

方法二:使用配置类绑定(更规范的工程化方式)

如果需要在多个页面复用配置,或者要做属性校验、复杂处理,推荐用配置类绑定:

  1. 创建配置类,绑定image前缀的配置属性:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "image")
public class ImageProperties {
    private String url;

    // Getter & Setter
    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}
  1. 在Thymeleaf模板中直接引用配置类的属性:
<img th:src="${@imageProperties.url}" />

关键提示

  • 启动应用时需指定激活环境:开发环境添加启动参数--spring.profiles.active=dev,生产环境可省略或指定--spring.profiles.active=prod。
  • 你提供的application-dev.yaml中image.url值为prod-env-link,这应该是笔误,请替换为开发环境的实际图片链接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 11:04:53