如何使用框架从外部有条件地注入bean(不创建工厂类)?
在下面的场景中,两个childBeans都已经实例化,但是在运行时根据条件注入到父bean中。
<bean id=ChildBean1>
<bean id=ChildBean2>
<parentBean name='parentBean' lazy-init="true">
<property name='flag'>
<somecondition flag=1/>
<property name='child' ref ='childBean1'/>
<somecondition flag=2/>
<property name='child' ref ='childBean2'/>
</parentBean>
答案 0 :(得分:1)
您可以通过弹簧表达语言(SpEL)来完成:
@Bean
public HelloBean helloBean() {
HelloBean helloBean = new HelloBean ();
if (condition) {
helloBean.setDependency(dependencyA());
} else {
helloBean.setDependency(dependencyB());
}
return helloBean;
}
也可以使用类似下面的Java Config:
total = 0
while True:
seat = raw_input("Enter value for the seat: ")
if seat == 'q':
break
try:
total += float(seat)
except ValueError:
print("Not a valid float value; ignoring")
print("Total is {0}".format(total))