Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolating environment variables in string

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.

like image 683
Sagebrush Gardener Avatar asked Aug 11 '26 10:08

Sagebrush Gardener


1 Answers

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;
        }
    }
}
like image 154
Sagebrush Gardener Avatar answered Aug 14 '26 16:08

Sagebrush Gardener