Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a spring bean for a Java double primitive?

I'd like to create a spring bean that holds the value of a double. Something like:

<bean id="doubleValue" value="3.7"/>
like image 852
Alex B Avatar asked Sep 12 '08 20:09

Alex B


2 Answers

Declare it like this:

<bean id="doubleValue" class="java.lang.Double">
   <constructor-arg index="0" value="3.7"/>
</bean>

And use like this:

<bean id="someOtherBean" ...>
   <property name="value" ref="doubleValue"/>
</bean>
like image 133
Pavel Feldman Avatar answered Sep 23 '22 06:09

Pavel Feldman


It's also worth noting that depending on your need defining your own bean may not be the best bet for you.

<util:constant static-field="org.example.Constants.FOO"/>

is a good way to access a constant value stored in a class and default binders also work very well for conversions e.g.

<bean class="Foo" p:doubleValue="123.00"/>

I've found myself replacing many of my beans in this manner, coupled with a properties file defining my values (for reuse purposes). What used to look like this

<bean id="d1" class="java.lang.Double">
  <constructor-arg value="3.7"/>
</bean>
<bean id="foo" class="Foo">
  <property name="doubleVal" ref="d1"/>
</bean>

gets refactored into this:

<bean
  id="propertyFile"
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
  p:location="classpath:my.properties"
/>
<bean id="foo" class="Foo" p:doubleVal="${d1}"/>
like image 36
enricopulatzo Avatar answered Sep 21 '22 06:09

enricopulatzo