Spring Expression Language使用其他Bean更改Bean属性

时间:2019-05-11 18:27:09

标签: java spring spring-boot spring-el

我有一个具有“ creditAmount”之类的属性的Customer bean,我将其作为请求正文接收,并希望将其持久化到数据库中。在将其持久化之前,我想应用表达式,例如,如果“ creditamount”为null或小于0,则应将其设置为0。

我还有另一个具有字符串属性“ creditAmountExpression”的bean CustomerExpression,该字符串属性是从数据库中填充的,表达式为“((creditAmount eq null或creditAmount le 0?0:creditAmount)”)。

因此,现在我有两个bean Customer和CustomerExpression,并且想要将表达式从CustomerExpression bean的“ creditAmountExpression”属性动态地应用于Customer bean的“ creditAmount”字段,并设置其值。

我使用StandardEvaluationContext和SpelExpressionParser类进行了尝试。我可以获取表达式执行的值,但无需显式调用setValue()就可以更改属性的值。

@Autowired
SpelExpressionParser spelExpressionParser;

CustomerExpression customerExpression  = getCustomerExpression();//populate 
from database .i.e creditAmountExpression = (creditAmount eq null or creditAmount le 0 ? 0 : creditAmount)".

Customer cust = new Customer();//creditAmount is null here

StandardEvaluationContext sEvalContext = new StandardEvaluationContext(cust);
// we can get value as below but cant change it directly

 Integer value = spelExpressionParser.parseExpression(customerExpression.getCreditAmountExpression()).getValue(context,Integer.class);

以上行返回0,因为信用额为空,但我想更改属性值

在应用

中的表达式后,应将Customer.creditAmount的

值更新为0

CustomerExpression.getCreditAmountExpression()

使用CustomerExpression bean的相应属性,对于Customer bean的所有属性应该相同。

0 个答案:

没有答案