java 将 int 传递给 spring 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14833272/
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
Passing int to spring property
提问by Mawia
I want to pass intinstead of stringwhich is default in spring PropertyPlaceholderConfigurer.
我想传递int而不是string,这是 spring PropertyPlaceholderConfigurer 中的默认值。
<property name="mailServerPort" value="${mail.port}" />
This give me error because mailServerPort is int type and ${mail.port} is string type.
这给了我错误,因为 mailServerPort 是 int 类型而 ${mail.port} 是字符串类型。
How can I convert ${mail.port} to int?
如何将 ${mail.port} 转换为 int?
回答by Japan Trivedi
According to me the casting should work properly if the value of port is proper integer.
根据我的说法,如果 port 的值是正确的整数,则转换应该正常工作。
Still if you face the problem you can try SpringExpressionLanguage(SpEL) for conversion.
尽管如此,如果您遇到问题,您可以尝试使用 SpringExpressionLanguage(SpEL) 进行转换。
<property name="mailServerPort" value="#{ T(java.lang.Integer).parseInt(mail.port) }"/>
Hope this helps you.
希望这对你有帮助。
回答by BobTheBuilder
Spring handles conversion based on the target type if possible.
如果可能,Spring 会根据目标类型处理转换。
Are you sure you set
你确定你设置
mail.port
value with int?
值与int?
回答by Shankar Chourasia
The Spring should handle it automatically, although if it is giving error, you can use the typeattribute property tag and provide and specify require type. For Ex.
Spring 应该自动处理它,尽管如果它给出错误,您可以使用type属性属性标记并提供和指定需要类型。对于前。
<property name="mailServerPort" type="int" value="${mail.port}" />
Hope this helps.. :-)
希望这可以帮助.. :-)
回答by Ivan Pronin
All above answers will work ok in case property value is provided. If it's empty you may use SpringExpressionLanguage to handle that case and provide a default value:
如果提供了属性值,上述所有答案都可以正常工作。如果它是空的,你可以使用 SpringExpressionLanguage 来处理这种情况并提供一个默认值:
<property name="mailServerPort" value="#{ '${mail.port}'.isEmpty() ? '8080' : '${mail.port}' }"/>