简体   繁体   中英

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

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

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>

Since Spring 3.0, you can use 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"/>

You should be able to do:

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

See section 3.3.1.1.1.1 of the Spring Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM