如何使用框架有条件地从外部注入(inject) Bean(不创建工厂类)?
在下面的场景中,两个 childBean 都已经实例化,但在运行时根据条件注入(inject)到父 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>
最佳答案
您可以通过 spring 表达式语言(SpEL)来完成:
<bean class="com.example.spring.TestBean">
<property name="dependency" value="#{systemProperties['profile'] == 'test' ? dependencyA : dependencyB}" />
</bean>
也可以使用如下所示的 Java 配置:
@Bean
public HelloBean helloBean() {
HelloBean helloBean = new HelloBean ();
if (condition) {
helloBean.setDependency(dependencyA());
} else {
helloBean.setDependency(dependencyB());
}
return helloBean;
}
关于java - Spring IoC : Conditional Injection in run time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37427165/