【问题标题】:How to get SpEL to add two numbers如何让SpEL将两个数字相加
【发布时间】:2015-01-06 12:06:27
【问题描述】:

我想在 application.properties 中计算我的端口号,如下所示:

server.port=#{ 1 + ${myapp.web.server.port.ssl} }
myapp.web.server.port.ssl=8300

但是当我启动我的 Spring Boot 应用程序时,我得到的只是一个执行。

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type java.lang.String to type java.lang.Integer]

reference guide 的数学运算符部分建议它应该可以工作,但事实并非如此。

在 Spring 内部,它可以调用:

GenericConversionService.convert("#{ 1 + 8300 }", java.lang.String, java.lang.Integer)

但是那里没有逻辑可以识别它是SpEL。就好像它根本不承认它是 SpEL。但是,如果我将表达式更改为 #{ n1 + ${myapp.web.server.port.ssl} },则会出现以下异常,表明它正在被评估为 SpEL:

SpelEvaluationException: EL1008E:(pos 0): Property or field 'n1' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?

如何让 SpEL 为另一个属性的值加一?

更新:

我找到了similar question,所以我尝试了类似的方法:

server.port=#{T(java.lang.Integer).parseInt('${fire.web.server.port.ssl}') + 1}

但这仍然行不通。由于某种原因,它没有将其视为 SpEL 表达式。但是如果存在语法错误,它确实将其视为 SpEL 表达式!

【问题讨论】:

  • 成功了吗?
  • 哇哦,我不记得了,这是 5 年前的事了。

标签: java spring spring-el


【解决方案1】:

您只能从配置中做到这一点,但不能从属性中做到这一点:

<bean class="...">
   <property name="port" value="#{1 + ${myapp.web.server.port.ssl}}"/>
</bean>

【讨论】:

  • 我认为你可能是对的。但这并不完全有意义,好像我输入 #{ n1 + ${myapp.web.server.port.ssl} } 然后我得到 SpEL 异常。因此,在某种程度上,它将其视为 SpEL 表达式!
  • 确实如此,因为 SpEL 不知道 n1 是什么。如果它是文件中的属性,您也应该像 ${n1} 一样使用它。如果您有一个名称为n1 的bean,它将起作用。否则是的:即使对我来说也没有意义。
  • 但是如果我将 n1 更改为 1,那么我会得到一个非 SpEL 异常,说它无法将字符串转换为整数,并且堆栈跟踪中没有提到 SpEL。所以就好像它没有被视为 SpEL 表达式。
  • 这个#{1 + Integer.parseInt(${myapp.web.server.port.ssl})}怎么样?
【解决方案2】:

我认为问题在于${myapp.web.server.port.ssl} 被评估为String,试试这样的

#{1 + new Integer(props['myapp.web.server.port.ssl'])}

props 是持有你的属性的 bean。

【讨论】:

  • 谢谢,但这不起作用,因为我没有 props 作为对象。更新问题。
  • 你能试试这个#{1 + new Integer(myapp.web.server.port.ssl)}吗?
猜你喜欢
  • 2019-06-23
  • 1970-01-01
  • 1970-01-01
  • 2010-10-01
  • 1970-01-01
  • 2011-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多