Interpolating environment variables in string

别来无恙 提交于 2020-01-25 00:19:08

问题


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

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

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.

Notes:

  1. This is not a duplicate of the many "variable interpolation in java strings" questions. I need to interpolate environment variables in the specific format ${ENV_VAR}.

  2. 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.

  3. 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.


回答1:


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/

To summarize:

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://stackoverflow.com/questions/58770380/interpolating-environment-variables-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!