Do I have any known way to inject beans in spring IoC container based on some condition. E.g. I have two beans:
<bean id="aaa" class="My"/>
<bean id="bbb" class="My"/>
... and want inject it in another bean based on开发者_如何学Python following rule:
Inject "aaa" if "aaa" isn't null or inject "bbb" in other case
Thanks
You can use JavaConfig - there you can use java code to implement this logic. I've never used it, but taking an example from the docs:
@Configuration
public class ServiceConfig {
private @Resource(name="aaa") Aaa aaa;
private @Resource(name="bbb") Aaa bbb;
public @Bean TransferService transferService() {
TransferService service = new TransferServiceImpl();
if (aaa != null) {
service.setProperty(aaa);
} else {
service.setProperty(bbb);
}
return service;
}
}
Another option is to use a FactoryBean
to encapsulate that logic - the factory bean can lookup a bean in the context, and if found - return it. If not found - lookup another bean.
If you are on spring 3.0 this can be achieved using SpEL - Expression langauge support.
精彩评论