在字符串中插值环境变量

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

statsFile=${APP_LOG_DIR}/app.stats

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

这似乎是一个非常普遍的需求,诸如Logback框架之类的事情针对它们自己的配置文件执行此操作,但是我还没有找到对自己的配置文件执行此操作的规范方法。

注意:

  1. 这不是许多“ java字符串中的变量插值”问题的重复项。我需要以特定格式$ {ENV_VAR}插入 environment 变量。

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

  3. 其他语言(例如go)为此具有一个简单的内置函数:Interpolate a string with bash-like environment variables references。我正在寻找Java类似的东西。

wow_365763491 回答:在字符串中插值环境变量

回答我自己的问题。感谢以上评论中Expand environment variables in text中@radulfr链接的线索,我使用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;
        }
    }
}
本文链接:https://www.f2er.com/3136461.html

大家都在问