在字符串中插值环境变量
我需要在字符串中扩展环境变量.例如,当解析配置文件时,我希望能够读取此文件...
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.
注意:
-
这不是许多"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.
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;
}
}
}