具有动态构造函数值的Spring bean [英] spring bean with dynamic constructor value
问题描述
我需要创建一个没有构造函数参数的不完整对象.像这样
I need to create an Object which is in-complete without the constructor argument. Something like this
Class A {
private final int timeOut
public A(int timeout)
{
this.timeOut = timeout;
}
//...
}
我希望这个Bean是Spring管理的,以便以后可以使用Spring AOP.
I would like this Bean to be spring managed, so that I can use Spring AOP later.
<bean id="myBean" class="A" singleton="false">
</bean>
但是我的bean需要将超时作为动态值传递-有没有一种方法可以创建在构造函数中注入了动态值的spring托管bean?
However my bean needs timeout to be passed as a dynamic value - is there a way to create a spring managed bean with dynamic value being injedcted in the constructor?
推荐答案
BeanFactory
具有getBean(String name, Object... args)
方法,根据
BeanFactory
has a getBean(String name, Object... args)
method which, according to the javadoc, allows you to specify constructor arguments which are used to override the bean definition's own arguments. So you could put a default value in the beans file, and then specify the "real" runtime values when required, e.g.
<bean id="myBean" class="A" scope="prototype">
<constructor-arg value="0"/> <!-- dummy value -->
</bean>
然后:
getBean("myBean", myTimeoutValue);
我还没有尝试过,但是应该可以.
I haven't tried this myself, but it should work.
P.S. scope="prototype"
现在比singleton="false"
更可取,后者已被弃用-更加明确,但功能相同.
P.S. scope="prototype"
is now preferable to singleton="false"
, which is deprecated syntax - it's more explicit, but does the same thing.
这篇关于具有动态构造函数值的Spring bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!