gpt4 book ai didi

java - Spring Evaluate Placeholder In Java,模拟@Value注解

转载 作者:行者123 更新时间:2023-11-29 08:30:07 25 4
gpt4 key购买 nike

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

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

最佳答案

您可以使用 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
}
}

关于java - Spring Evaluate Placeholder In Java,模拟@Value注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49114121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com