@Value注释类型铸造整数字符串 [英] @Value annotation type casting to Integer from String

查看:1173
本文介绍了@Value注释类型铸造整数字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个值的输出转换为一个整数:

I'm trying to cast the output of a value to an integer:

@Value("${api.orders.pingFrequency}")
private Integer pingFrequency;

以上引发错误

org.springframework.beans.TypeMismatchException: 
    Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; 
nested exception is java.lang.NumberFormatException: 
    For input string: "(java.lang.Integer)${api.orders.pingFrequency}"

我也试过 @Value((java.lang.Integer中)$ {api.orders.pingFrequency})

谷歌似乎并没有说太多关于这个问题的。我想始终与整数处理,而不必到处解析这个值,用它。

Google doesn't appear to say much on the subject. I'd like to always be dealing with an integer instead of having to parse this value everywhere it's used.

解决方法

我认识一个解决办法可能是使用setter方法​​来运行转换对我来说,但如果春节能做到这一点,我宁愿学到一些关于Spring。

I realize a workaround may be to use a setter method to run the conversion for me, but if Spring can do it I'd rather learn something about Spring.

推荐答案

假设你有一个特性在classpath文件,它包含

Assuming you have a properties file on your classpath that contains

api.orders.pingFrequency=4

我试过在 @Controller

@Controller
public class MyController {     
    @Value("${api.orders.pingFrequency}")
    private Integer pingFrequency;
    ...
}

通过包含我的servlet上下文:

With my servlet context containing :

<context:property-placeholder location="classpath:myprops.properties" />

它的工作完美。

It worked perfectly.

因此​​,无论您的属性不是整数类型,你不必属性占位符配置正确,或者你使用了错误的属性键。

So either your property is not an integer type, you don't have the property placeholder configured correctly, or you are using the wrong property key.

我试着用一个无效的属性值, 4123运行; 。我得到的例外是

I tried running with an invalid property value, 4123;. The exception I got is

java.lang.NumberFormatException: For input string: "4123;"

这让我想起你的财产的价值

which makes me think the value of your property is

api.orders.pingFrequency=(java.lang.Integer)${api.orders.pingFrequency}

这篇关于@Value注释类型铸造整数字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆