tags:

views:

48

answers:

2

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>
+2  A: 

You should be able to do:

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

See section 3.3.1.1.1.1 of the Spring Reference

Kevin
Doesn't really solve this problem, though, or am I missing something?
jamie mccrindle
I thought you wanted to be have spring force a value to a certain type without verbosely declaring the type.
Kevin
the issue here really has more to do with using the jee xml namespace
matt b
@Kevin - ah, ok, I had a look at my question and I mentioned both contructors and properties. So yes, this solves it for constructors. I guess I should have mentioned properties specifically because they're what are killing me in this case.
jamie mccrindle
@Matt - the jee namespace isn't great because the "default-value" is defined as a string. The second bit of XML is better, though, because defaultValue can be any object but the explicit <bean class="...Integer"/> is then required to force Spring to make the defaultObject an Integer rather than a String.
jamie mccrindle
+1  A: 

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