Bill
Bill

Reputation: 53

Spring Evaluate Placeholder In Java, Emulate @Value annotation

I'm looking for the following behavior when parsing a string:

+----------------------------+-----------------+
|         Parameter          |     Result      |
+----------------------------+-----------------+
| Account                    | Account         |
| ${spring.application.name} | DemoApplication |
| ${missing:defaultValue}    | defaultValue    |
+----------------------------+-----------------+

I've tried using SpelExpressionParser and the Environment bean with no luck. Essentially, I'm looking for the functionality of the @Value annotation, but in Java code.

Examples:

private final Environment environment;
public void exampleMethod() {
    String value = environment.getProperty("spring.application.name"); //Works
    String value2 = environment.getProperty("${spring.application.name}"); //Does not work


    ExpressionParser parser = new SpelExpressionParser();

    String value3 = parser.parseExpression("spring.application.name").getValue(String.class);
    // Throws exception SpelEvaluationException: EL1007E: Property or field 'spring' cannot be found on null

    String value4 = parser.parseExpression("${spring.application.name}").getValue(String.class);
    // Throws the exception: SpelParseException: EL1041E: After parsing a valid expression, there is still more data in the expression: 'lcurly({)'
}

Upvotes: 2

Views: 1414

Answers (1)

Strelok
Strelok

Reputation: 51461

You can use the Environment class to resolve placeholders against it.

public class TestPlaceholders {
        @Autowired
        Environment environment;

        public void testPlaceHolders() {
            environment.resolveRequiredPlaceholders("${spring.application.name}"); // your-app-name
            environment.resolveRequiredPlaceholders("${bad.prop:missing}"); // missing
            environment.resolveRequiredPlaceholders("NoPlaceholders"); // NoPlaceholders
        }
    }

Upvotes: 7

Related Questions