题
我想创建一个春季豆持有的价值的一倍。是这样的:
<bean id="doubleValue" value="3.7"/>
解决方案
声明它是这样的:
<bean id="doubleValue" class="java.lang.Double">
<constructor-arg index="0" value="3.7"/>
</bean>
并使用这样的:
<bean id="someOtherBean" ...>
<property name="value" ref="doubleValue"/>
</bean>
其他提示
这也是值得注意的是,这取决于你的需要限定你自己的豆可能不是你最好的选择。
<util:constant static-field="org.example.Constants.FOO"/>
是一个很好的方式来访问的一个常数值储存在一类和默认的粘合剂也很好地工作的转换,例如
<bean class="Foo" p:doubleValue="123.00"/>
我发现我自己更换我的许多豆以这种方式,加上一个属性的文件限定了我的价值(重复使用目的)。用什么看起来像这样
<bean id="d1" class="java.lang.Double">
<constructor-arg value="3.7"/>
</bean>
<bean id="foo" class="Foo">
<property name="doubleVal" ref="d1"/>
</bean>
得到重构成:
<bean
id="propertyFile"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:my.properties"
/>
<bean id="foo" class="Foo" p:doubleVal="${d1}"/>
为什么你不用 双?任何原因吗?
弹簧2.5+
你可以定义豆这样Java配置:
@Configuration
public class BeanConfig {
@Bean
public Double doubleBean(){
return new Double(3.7);
}
}
你可以使用这个豆喜欢这个在你的程序:
@Autowired
Double doubleBean;
public void printDouble(){
System.out.println(doubleBean); //sample usage
}
不隶属于 StackOverflow