ou can implement simple factory bean to do the conditional wiring. Such factory bean can contain complex conditioning logic:

public MyBeanFactoryBean implements FactoryBean<MyBean> {

    // Using app context instead of bean references so that the unused
// dependency can be left uninitialized if it is lazily initialized
@Autowired
private ApplicationContext applicationContext; public MyBean getObject() {
MyBean myBean = new MyBean();
if (true /* some condition */) {
myBean.setDependency(applicationContext.getBean(DependencyX.class));
} else {
myBean.setDependency(applicationContext.getBean(DependencyY.class));
}
return myBean;
} // Implementation of isSingleton => false and getObjectType }

Maybe a bit better approach is if you use factory bean to create the dependency bean in case you want to have only one such bean in your application context:

public MyDependencyFactoryBean implements FactoryBean<MyDependency> {

    public MyDependency getObject() {
if (true /* some condition */) {
return new MyDependencyX();
} else {
return new MyDependencyY();
}
} // Implementation of isSingleton => false and getObjectType }

SpEL

With SpEL there are many possibilities. Most common are system property based conditions:

<bean class="com.example.MyBean">
<property name="dependency" value="#{systemProperties['foo'] == 'bar' ? dependencyX : dependencyY}" />
</bean>

Property placeholder

You can have property placeholder resolve your bean reference. The dependency name can be part of the application configuration.

<bean class="com.example.MyBean">
<property name="dependency" ref="${dependencyName}" />
</bean>

Spring profiles

Usually the condition you want to evaluate means that a whole set of beans should or should not be registered. Spring profiles can be used for this:

<!-- Default dependency which is referred by myBean -->
<bean id="dependency" class="com.example.DependencyX" /> <beans profile="myProfile">
<!-- Override `dependency` definition if myProfile is active -->
<bean id="dependency" class="com.example.DependencyY" />
</beans>

Other methods can mark the bean definition as lazy-init="true", but the definition will be still registered inside application context (and making your life harder when using unqualified autowiring). You can also use profiles with @Component based beans via @Profile annotation.

Check ApplicationContextInitialier (or this example) to see how you can activate profiles programatically (i.e. based on your condition).

Java config

This is why Java based config is being so popular as you can do:

@Bean
public MyBean myBean() {
MyBean myBean = new MyBean();
if (true /* some condition */) {
myBean.setDependency(dependencyX());
} else {
myBean.setDependency(dependencyY());
}
return myBean;
}

Of course you can use more or less all configuration methods in the java based config as well (via @Profile@Value or @Qualifier + @Autowired).

Post processor

Spring offers numerous hook points and SPIs, where you can participate in the application context life-cycle. This section requires a bit more knowledge of Spring's inner workings.

BeanFactoryPostProcessors can read and alter bean definitions (e.g. property placeholder ${}resolution is implemented this way).

BeanPostProcessors can process bean instances. It is possible to check freshly created bean and play with it (e.g. @Scheduled annotation processing is implemented this way).

MergedBeanDefinitionPostProcessor is extension of bean post processor and can alter the bean definition just before it is being instantiated (@Autowired annotation processing is implemented this way).


UPDATE Oct 2015

  • Spring 4 has added a new method how to do conditional bean registration via @Conditionalannotation. That is worth checking as well.

  • Of course there are numerous other ways with Spring Boot alone via its @ConditionalOn*.

  • Also note that both @Import and @ComponentScan (and their XML counterparts) undergo property resolution (i.e. you can use ${}).

How to do conditional auto-wiring in Spring?的更多相关文章

  1. Wiring in Spring: @Autowired, @Resource and @Inject 区别

    refer:https://www.baeldung.com/spring-annotations-resource-inject-autowire 主要是查找顺序不一致: @Resource Mat ...

  2. 69 Spring Interview Questions and Answers – The ULTIMATE List--reference

    This is a summary of some of the most important questions concerning the Spring Framework, that you ...

  3. spring学习总结——高级装配学习一(profile与@Conditional)

    前言: 在上一章装配Bean中,我们看到了一些最为核心的bean装配技术.你可能会发现上一章学到的知识有很大的用处.但是,bean装配所涉及的领域并不仅仅局限于上一章 所学习到的内容.Spring提供 ...

  4. Spring Framework 条件装配 之 @Conditional

    Spring Framework 条件装配 之 @Conditional 前言 了解SpringBoot的小伙伴对Conditional注解一定不会陌生,在SpringBoot项目中,Conditio ...

  5. Spring Autowiring by AutoDetect

    In Spring, "Autowiring by AutoDetect", means chooses "autowire by constructor" i ...

  6. Spring Autowiring by Constructor

    In Spring, "Autowiring by Constructor" is actually autowiring by Type in constructor argum ...

  7. Spring Autowiring by Name

    In Spring, "Autowiring by Name" means, if the name of a bean is same as the name of other ...

  8. Spring Autowiring by Type

    In Spring, "Autowiring by Type" means, if data type of a bean is compatible with the data ...

  9. Spring Auto-Wiring Beans

    In Spring framework, you can wire beans automatically with auto-wiring feature. To enable it, just d ...

  10. Spring boot 配置文件详解 (properties 和yml )

    从其他框架来看 我们都有自己的配置文件, hibernate有hbm,mybatis 有properties, 同样, Spring boot 也有全局配置文件. Springboot使用一个全局的配 ...

随机推荐

  1. ip访问网站和localhost访问网站中top使用

    对于相对定位,使用margin-top不用简单使用top. top在localhost中能正常显示,在ip访问时会出现多余空白. margin-top不管是localhost中还是ip中都能正常显示.

  2. Rsync + Sersync 实现数据增量同步

    部分引用自:https://blog.csdn.net/tmchongye/article/details/68956808 一.什么是Rsync? Rsync(Remote Synchronize) ...

  3. BZOJ3230 相似子串 字符串 SA ST表

    原文链接http://www.cnblogs.com/zhouzhendong/p/9033092.html 题目传送门 - BZOJ3230 题意 给定字符串$s$.长度为$n$. 现在有$Q$组询 ...

  4. P1080 国王游戏 贪心 高精度

    题目描述 恰逢 HH国国庆,国王邀请nn 位大臣来玩一个有奖游戏.首先,他让每个大臣在左.右手上面分别写下一个整数,国王自己也在左.右手上各写一个整数.然后,让这 nn 位大臣排成一排,国王站在队伍的 ...

  5. 直接引用vee-validate校验插件

    直接在页面引用vee-validate 源文件下载地址:http://www.bootcdn.cn/vee-validate/ 官方api https://baianat.github.io/vee- ...

  6. POJ 3126 Prime Path【BFS】

    <题目链接> 题目大意: 给你两个四位数,它们均为素数,以第一个四位数作为起点,每次能够变换该四位数的任意一位,变换后的四位数也必须是素数,问你是否能够通过变换使得第一个四位数变成第二个四 ...

  7. Stm32基础

    Stm32基础 目录 常用功能函数 跑马灯实验 蜂鸣器实验 按键实验 端口复用与重映射 常用功能函数 初始化gpio函数 作用:初始化一个或者多个io口(同一组)的工作方式和速度该函数主要是操作GPI ...

  8. .NET Core 2.0应用程序大小减少50%

    .NET Core 2.0应用程序减小体积瘦身官方工具 IL Linker. IL Linker 来源于mono的linker  https://github.com/mono/linker,目前还是 ...

  9. python 多线程锁机制

    GIL(全局解释器锁) GIL并不是Python的特性,它是在实现Python解析器(CPython)时所引入的一个概念,是为了实现不同线程对共享资源访问的互斥,才引入了GIL 在Cpython解释器 ...

  10. VBA中FIND方法的使用说明zz

    Find 方法在区域中查找特定信息. 语法 表达式.Find(What, After, LookIn, LookAt, SearchOrder, SearchDirection, MatchCase, ...