Question

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

<bean id="doubleValue" value="3.7"/>
Was it helpful?

Solution

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>

OTHER TIPS

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

Why don't you just use a Double? any reason?

Spring 2.5+

You can define bean like this in Java config:

@Configuration
public class BeanConfig {
    @Bean
    public Double doubleBean(){
        return  new Double(3.7);
    }
}

You can use this bean like this in your program:

@Autowired
Double doubleBean;

public void printDouble(){
    System.out.println(doubleBean); //sample usage
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top