Reputation: 61
How can I conditionally inject a bean externally using the framework ( not creating a factory class)?
In below scenario both childBeans will be instantiated already while but injected into parent bean in run time based on condition.
<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>
Upvotes: 0
Views: 1346
Reputation: 1967
You can do it via spring expression language(SpEL):
<bean class="com.example.spring.TestBean">
<property name="dependency" value="#{systemProperties['profile'] == 'test' ? dependencyA : dependencyB}" />
</bean>
Also it is possible using a Java Config something like below:
@Bean
public HelloBean helloBean() {
HelloBean helloBean = new HelloBean ();
if (condition) {
helloBean.setDependency(dependencyA());
} else {
helloBean.setDependency(dependencyB());
}
return helloBean;
}
Upvotes: 1