简体   繁体   中英

Java method for resolving placeholder values against system properties and environmental variables

What is the appropriate, known Java method which helps us to resolve placeholder values such as ${catalina.base}/keystore.jks against system properties and environmental variables? For example they detect ${catalina.base} within ${catalina.base}/keystore.jks value and replace it with the appropriate value.

I found a good library which supports the intended puprose in org.apache.commons.lang3 . You can use its StrSubstitutor class for the purposes I have mentioned earlier.

Java does not provide built-in method to resolve placeholders.

You have to use some additional code.

Spring

You can use a PropertyResolver, for example:

As an example, the following code will resolve your system properties automatically:

String resolvedString = new StandardEnvironment().resolvePlaceholders("${catalina.base}/keystore.jks");

Alternatively, if your program uses Spring application context (or plan to use it), you can configure a PropertyPlaceholderConfigurer to resolve placeholder in configuration files automaticaly.

typesafehub config

As suggested by @Thilo, this library seem to do what you need.

See https://github.com/typesafehub/config#uses-of-substitutions

DIY

If you don't need Spring or typesafehub config (both will introduce complexity if you don't need them), I'd recommend that you develop a simple class to do it for you.

IMHO ~10-20 lines of code using regex or even a more basic parser could do the job for a simple case (ie: without recursive evaluation / dependency resolution).

This is how you read environment variables in Java:

    final Map<String, String> envMap = System.getenv();
    for (Map.Entry entry : envMap.entrySet())
    {
        System.out.println(entry.getKey() + " = " + entry.getValue());
    }

    final String path = System.getenv("PATH");
    System.out.println("PATH = " + path);

    final String catalinaBase = System.getenv("catalina.base");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM