在字符串中插值环境变量 [英] Interpolating environment variables in string

查看:128
本文介绍了在字符串中插值环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to expand environment variables in a string. For example, when parsing a config file, I want to be able to read this...

statsFile=${APP_LOG_DIR}/app.stats

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

And get a value of "/logs/myapp/app.stats", where the environment variable APP_LOG_DIR = "/logs/myapp".

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

This seems like a very common need, and things like the Logback framework do this for their own config files, but I have not found a canonical way of doing this for my own config files.

注意:

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

在此处提出了相同的问题,在字符串中扩展env变量 ,但答案需要Spring框架,而我不想仅仅为了完成一项简单的任务就引入这种巨大的依赖关系.

The same question was asked here, Expand env variables in String, but the answer requires the Spring framework, and I don't want to pull in this huge dependency just to do this one simple task.

其他语言(例如go)对此具有简单的内置功能:

Other languages, like go, have a simple built-in function for this: Interpolate a string with bash-like environment variables references. I am looking for something similar in java.

推荐答案

回答我自己的问题.感谢上面评论中@radulfr链接到以文本形式扩展环境变量的线索,我在这里使用StrSubstitutor找到了一个非常干净的解决方案: https ://dkbalachandar.wordpress.com/2017/10/13/how-to-use-strsubstitutor/

Answering my own question. Thanks to clues from @radulfr's link in the comments above to Expand environment variables in text, I found a pretty clean solution, using StrSubstitutor, here: 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;
        }
    }
}

这篇关于在字符串中插值环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆