【问题标题】:Interpolating environment variables in string在字符串中插入环境变量
【发布时间】:2019-11-08 16:25:29
【问题描述】:

我需要在字符串中展开环境变量。例如,在解析配置文件时,我希望能够读取这个...

statsFile=${APP_LOG_DIR}/app.stats

并获取“/logs/myapp/app.stats”的值,其中环境变量APP_LOG_DIR =“/logs/myapp”。

这似乎是一个非常普遍的需求,像 Logback 框架这样的东西为他们自己的配置文件执行此操作,但我还没有找到为我自己的配置文件执行此操作的规范方法。

注意事项:

  1. 不是许多“Java 字符串中的变量插值”问题的副本。我需要以特定格式 ${ENV_VAR} 插入 环境 变量。

  2. 同样的问题,Expand env variables in String,在这里提出了,但答案需要 Spring 框架,我不想为了完成这个简单的任务而引入这个巨大的依赖关系。

  3. 其他语言,比如 go,有一个简单的内置函数:Interpolate a string with bash-like environment variables references。我正在java中寻找类似的东西。

【问题讨论】:

  • 变量 APP_LOG_DIR 是环境变量还是配置文件中的属性?
  • APP_LOG_DIR 是一个环境变量,我想使用 ${APP_LOG_DIR} 语法在我的配置文件中引用它。
  • @radulfr,这看起来与我需要的相似。对于这样一个常见的需求,我在想会有一个不需要编写自己的函数的解决方案,但是如果我找不到更好的方法,这可能会起作用。

标签: java environment-variables string-interpolation


【解决方案1】:

回答我自己的问题。感谢上面 cmets 中 @radulfr 的链接到 Expand environment variables in text 的线索,我在这里找到了一个非常干净的解决方案,使用 StrSubstitutor:https://dkbalachandar.wordpress.com/2017/10/13/how-to-use-strsubstitutor/

总结一下:

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.StrLookup;
import org.apache.commons.lang3.text.StrSubstitutor;

public class StrSubstitutorMain {

    private static final StrSubstitutor envPropertyResolver = new StrSubstitutor(new EnvLookUp());

    public static void main(String[] args) {

        String sample = "LANG: ${LANG}";
        //LANG: en_US.UTF-8
        System.out.println(envPropertyResolver.replace(sample));

    }

    private static class EnvLookUp extends StrLookup {

        @Override
        public String lookup(String key) {
            String value = System.getenv(key);
            if (StringUtils.isBlank(value)) {
                throw new IllegalArgumentException("key" + key + "is not found in the env variables");
            }
            return value;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2017-03-02
    • 1970-01-01
    • 2014-08-16
    • 2020-10-07
    • 1970-01-01
    • 2011-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多