Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

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>
like image 484
Jamie McCrindle Avatar asked Jan 22 '10 17:01

Jamie McCrindle


2 Answers

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"/>
like image 194
axtavt Avatar answered Nov 01 '22 21:11

axtavt


You should be able to do:

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

See section 3.3.1.1.1.1 of the Spring Reference

like image 42
Kevin Avatar answered Nov 01 '22 23:11

Kevin