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

如何在Freemarker中使用properties配置文件的键值对

Freemarker使用properties配置文件键值对的实现方案

方案1:Java层加载配置后传入数据模型(最推荐)

这是性能最优、维护成本最低的实现方式,步骤如下:

  • 首先在Java代码中加载properties文件,将所有键值对存入Freemarker渲染所需的数据模型中,示例代码:
import java.io.InputStream;
import java.util.Properties;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;

// 加载properties文件
Properties configProps = new Properties();
try (InputStream inputStream = getClass().getResourceAsStream("/你自己的配置文件路径.properties")) {
    configProps.load(inputStream);
}
// 构造Freemarker数据模型,将配置全部存入
Map<String, Object> dataModel = new HashMap<>();
dataModel.putAll(configProps);
// 后续正常调用模板渲染逻辑即可
  • 模板中可以直接使用所有properties中的键作为变量,不需要额外assign:
    直接写${key1}就会输出value1,如果需要自定义变量名,再用assign赋值即可:
<#assign variable1 = key1>
<#assign variable2 = key2>

如果是Spring/SpringBoot项目,操作更简单:
可以通过@ConfigurationProperties加载配置类,或者直接将Environment对象放入数据模型,模板中调用${env.getProperty("key1")}即可获取值。

方案2:封装全局方法在模板中读取(仅适合特殊场景)

如果你无法在Java层修改数据模型,可以自定义Freemarker方法封装配置读取逻辑,注册为全局共享变量后在模板内调用:

  • 首先实现读取配置的自定义方法类:
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import freemarker.template.SimpleScalar;
import java.io.InputStream;
import java.util.Properties;
import java.util.List;

public class ReadPropertiesMethod implements TemplateMethodModelEx {
    private static final Properties CONFIG_PROPS = new Properties();
    // 静态加载配置,仅初始化一次
    static {
        try (InputStream inputStream = ReadPropertiesMethod.class.getResourceAsStream("/你自己的配置文件路径.properties")) {
            CONFIG_PROPS.load(inputStream);
        } catch (Exception e) {
            throw new RuntimeException("配置文件加载失败", e);
        }
    }

    @Override
    public Object exec(List arguments) throws TemplateModelException {
        if (arguments.isEmpty()) return null;
        String key = ((SimpleScalar) arguments.get(0)).getAsString();
        return CONFIG_PROPS.getProperty(key);
    }
}
  • 将自定义方法注册为Freemarker全局变量:
// configuration是你初始化的Freemarker.Configuration实例
configuration.setSharedVariable("readConfig", new ReadPropertiesMethod());
  • 模板中直接调用方法赋值即可:
<#assign variable1 = readConfig("key1")>
<#assign variable2 = readConfig("key2")>

注意:方案2会增加模板的业务逻辑侵入性,也不利于配置缓存,非特殊场景优先使用方案1。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 22:24:02