Java 在 Spring XML 中声明整数、双精度数、浮点数、字符串等
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2119057/
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
Declaring Integers, Doubles, Floats, Strings etc. in Spring XML
提问by Jamie McCrindle
Occasionally, Spring can't figure out what type a "value" should be. This happens when the property or constructor is of type "java.lang.Object". In these cases, Spring defaults to "java.lang.String". Sometimes this isn't the right choice, for example when using:
有时,Spring 无法弄清楚“值”应该是什么类型。当属性或构造函数的类型为“java.lang.Object”时会发生这种情况。在这些情况下,Spring 默认为“java.lang.String”。有时这不是正确的选择,例如在使用时:
<jee:jndi-lookup id="test" jndi-name="java:comp/env/test"
default-value="10" expected-type="java.lang.Integer"/>
If the lookup fails and it has to fall back to the default-value, there's a type mismatch. So, instead, this needs to be done:
如果查找失败并且必须回退到默认值,则存在类型不匹配。因此,相反,需要这样做:
<bean id="test" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/test" />
<property name="defaultObject">
<bean class="java.lang.Integer">
<constructor-arg value="10" />
</bean>
</property>
</bean>
which is somewhat verbose, especially if there are lots of them. Is there some handy way to declare an Integer / Long / Double / Float / String literal without having to use this format:
这有点冗长,特别是如果有很多的话。有没有一些方便的方法来声明一个整数/长/双/浮点数/字符串文字而不必使用这种格式:
<bean class="java.lang.Integer">
<constructor-arg value="10" />
</bean>
采纳答案by axtavt
Since Spring 3.0, you can use Spring Expression Language: #{new Integer(10)}
从 Spring 3.0 开始,您可以使用 Spring 表达式语言: #{new Integer(10)}
<jee:jndi-lookup id="test" jndi-name="java:comp/env/test"
default-value="#{new Integer(10)}" expected-type="java.lang.Integer"/>
回答by Kevin
You should be able to do:
你应该能够做到:
<constructor-arg value="10" type="int"/>
See section 3.3.1.1.1.1 of the Spring Reference
参见Spring Reference 的3.3.1.1.1.1 节