Declaring Integers, Doubles, Floats, Strings etc. in Spring XML

Jam*_*dle 14 java spring

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:

<jee:jndi-lookup id="test" jndi-name="java:comp/env/test" 
   default-value="10" expected-type="java.lang.Integer"/>
Run Code Online (Sandbox Code Playgroud)

如果查找失败并且必须回退到默认值,则表示类型不匹配.所以,相反,这需要做:

  <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>
Run Code Online (Sandbox Code Playgroud)

这有点冗长,特别是如果它们很多的话.是否有一些方便的方法来声明一个Integer/Long/Double/Float/String文字,而不必使用这种格式:

      <bean class="java.lang.Integer">
        <constructor-arg value="10" />
      </bean>
Run Code Online (Sandbox Code Playgroud)

axt*_*avt 14

从Spring 3.0开始,您可以使用Spring Expression Language: #{new Integer(10)}

<jee:jndi-lookup id="test" jndi-name="java:comp/env/test" 
    default-value="#{new Integer(10)}" expected-type="java.lang.Integer"/>
Run Code Online (Sandbox Code Playgroud)

  • 你也可以使用较短的`default-value ="#{10}"` (4认同)

Kev*_*vin 5

你应该能够做到:

<constructor-arg value="10" type="int"/>
Run Code Online (Sandbox Code Playgroud)

请参见Spring Reference的 3.3.1.1.1.1节