java Spring 表达式语言 (SpEL):将 String 解析为 int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10619624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:52:01  来源:igfitidea点击:

Spring expression language (SpEL): parse String to int

javaspringspring-el

提问by Jan Van den bosch

I've got a (String, obviously) property expressed in minutes that I want to convert to an intbefore I do some arithmetic and inject it into my Spring bean. Right now I have this SpEL expression:

我有一个String以分钟表示的 ( ,显然) 属性,int在我做一些算术并将其注入我的 Spring bean 之前,我想将其转换为 an 。现在我有这个 SpEL 表达式:

#{T(java.lang.Integer).parseInt(myProperties['MIN_TIME']) * 60 * 1000}

where myPropertiesis a simple java.util.Propertiesbean.

哪里myProperties有一个简单的java.util.Propertiesbean。

Not that I'm particularly annoyed by this expression, but nevertheless: does the SpEL have a prettier, built-in way to parse strings into numeric values?

并不是说我对这个表达式特别恼火,但是:SpEL 是否有更漂亮的内置方法来将字符串解析为数值?

Thanks!

谢谢!

回答by artbristol

Doesn't look like it, e.g. look at how the developers create them here: https://jira.springsource.org/browse/SPR-8716

看起来不像,例如看看开发人员如何在这里创建它们:https: //jira.springsource.org/browse/SPR-8716

A slightly shorter version could be

一个稍短的版本可能是

#{new Integer(myProperties['MIN_TIME']) * 60 * 1000}

回答by user2663570

Another way to do this is to use the util namespace to define a properties bean, ... xmlns:util="http://www.springframework.org/schema/util" ... http://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-3.1.xsd...

另一种方法是使用 util 命名空间来定义属性 bean,... xmlns:util="http://www.springframework.org/schema/util" ... http://www.springframework。 org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd...

<util:properties id="apiProperties"
    location="classpath:/api.properties" />

then use the alternate syntax for the properties bean

然后使用属性 bean 的替代语法

@Value("#{apiProperties['api.orders.pingFrequency']}")
private Integer pingFrequency;

The spring util properties bean generated by context will do the parse and conversion before assigning the value.

由上下文生成的 spring util 属性 bean 将在分配值之前进行解析和转换。