Spring在Java中评估占位符,模拟@Value注释

时间:2018-03-05 15:40:56

标签: java spring spring-boot

解析字符串时我正在寻找以下行为:

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

我尝试过使用SpelExpressionParserEnvironment bean没有运气。本质上,我正在寻找@Value注释的功能,但是在Java代码中。

示例:

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({)'
}

1 个答案:

答案 0 :(得分:2)

您可以使用Environment类来解析占位符。

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
        }
    }