有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在SpringXML中声明整数、双精度、浮点、字符串等

有时,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"/>

如果查找失败并且必须返回默认值,则存在类型不匹配。因此,需要这样做:

  <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>

这有点冗长,特别是如果有很多的话。是否有一些简便的方法来声明整数/长/双精度/浮点/字符串文字,而不必使用此格式:

      <bean class="java.lang.Integer">
        <constructor-arg value="10" />
      </bean>

共 (2) 个答案

  1. # 1 楼答案

    您应该能够做到:

    <constructor-arg value="10" type="int"/>
    

    Spring Reference第3.3.1.1.1.1节

  2. # 2 楼答案

    自Spring3.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"/>