开发者

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

开发者 https://www.devze.com 2022-12-17 16:11 出处:网络
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.St

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 r开发者_StackOverflow社区ight 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

0

精彩评论

暂无评论...
验证码 换一张
取 消