java 将Spring EL与默认变量一起使用以从属性中获取值时出现问题

of1yzvn4  于 10个月前  发布在  Java
关注(0)|答案(1)|浏览(66)

我试图使用SpEL来解决我的应用程序.yml文件中的变量,但我遇到了一些问题。
我的应用程序.yml文件看起来像这样:

myapp:
  componentOne:
    name: "helloWorld"

字符串
一个单独的.yml文件看起来像这样:

other:
  config: "componentOne"


我尝试使用Spring SpelExpressionParser如下:

public MyClass {
  @Autowired
  Helper helper;

  public StringValueResolver stringResolver;

  public void someMethod() {
    ExpressionParser parser = new SpelExpressionParser();
    Expression exp = parser.parseExpression("#environment['myapp.' + helper.getVar() + '.name']");
    String name = exp.getValue(String.class);
  }
}


public void someMethod() {
  ExpressionParser parser = new SpelExpressionParser();
  Expression exp = parser.parseExpression("#environment['myapp.' + stringResolver.resolveStringValue(helper.getVar()) + '.name']");
  String name = exp.getValue(String.class);
}


helper.getVar()输出 ${other.config}stringResolver.resolveStringValue(helper.getVar())输出 componentOne 均符合预期
我得到以下错误分别为上述代码块:

EL1007E: Property or field 'helper' cannot be found on null


EL1007E: Property or field 'stringResolver' cannot be found on null


我知道Spring可以解析我的变量,因为当我使用任何注解测试SpEL表达式时,例如@Value,变量被正确解析。下面的所有示例都可以工作,最后我从application.yml文件中得到了 helloWorld

@Value("#{environment['myapp.' + '${other.config}' + '.name']}")
@Value("#{environment['myapp.componentOne.name']}")
@MyCustomAnno("#{environment['myapp.' + '${other.config}' + '.name']}")
@MyCustomAnno("#{environment['myapp.componentOne.name']}")


我不能使用${other.config},因为它提供给Helper类,并在这里使用,所以我需要使用helper.getVar()方法,并且.yml文件可能会因模块而异。例如:

other:
  config: "componentTwo"
myapp:
  componentTwo:
    name: "foobar"
c0vxltue

c0vxltue1#

您可以将helper作为rootObject注册到Expression。然后,您的“getVar()”方法就可供计算器使用了。

Expression.getValue(Object rootObject,Class desiredResultType)

在默认上下文中根据指定的根对象计算表达式。
来源:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/expression/Expression.html

public void someMethod() {
  ExpressionParser parser = new SpelExpressionParser();
  Expression exp = parser.parseExpression("#environment[new String('myapp.') + getVar() + new String('.name')]");
  String name = exp.getValue(helper, String.class);
}

字符串
这里有更多关于这个东西的信息:
6.5.5方法
看看“societyContext”是如何被用作根对象的,它提供了对它的方法“isMember”的访问。* (在页面中搜索isMember的10个示例/见解)*
Society.java

相关问题