How to do conditional auto-wiring in Spring?

时间:2023-02-20 08:15:23

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&colon; &commat;Autowired&comma; &commat;Resource and &commat;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与&commat;Conditional)

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

  4. Spring Framework 条件装配 之 &commat;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 配置文件详解 &lpar;properties 和yml &rpar;

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

随机推荐

  1. php中引用&amp&semi;的真正理解-变量引用、函数引用、对象引用

    php的引用(就是在变量或者函数.对象等前面加上&符号) //最重要就是 删除引用的变量 ,只是引用的变量访问不了,但是内容并没有销毁 在PHP 中引用的意思是:不同的名字访问同一个变量内容. ...

  2. Maven简介与简单使用

    Maven项目对象模型(POM),可以通过一小段描述信息来管理项目的构建,报告和文档的软件项目管理工具. Maven 除了以程序构建能力为特色之外,还提供高级项目管理工具.由于 Maven 的缺省构建 ...

  3. mkimage的-a 和 –c参数和内核引导

    目录 一.mkimage工具简介二.-a参数与-e参数和内核引导的关系三.实例测试 3.1 -a参数与-e参数相同,可以将内核下载到SDRAM的任何地址,然后从这启动 3.2 -a参数与-e参数不同, ...

  4. Jquery的&dollar;命名冲突

    在Jquery中,$是JQuery的别名,所有使用$的地方也都可以使用JQuery来替换,如$('#msg')等同于JQuery('#msg')的写法.然而,当我们引入多个js库后,在另外一个js库中 ...

  5. node&period;async&period;auto

    资料 GITHUB async ASYNC详解—from csdn nodejs的高性能与灵活性让服务端开发变得有了些乐趣,最近在看nodejs在服务端的一些应用,觉得其npm下的众多开源包让其虽没有 ...

  6. Kendo UI开发教程&lpar;26&rpar;&colon; 单页面应用&lpar;四&rpar; Layout

    Layout继承自View,可以用来包含其它的View或是Layout.下面例子使用Layout来显示一个View 1 <div id="app"></div&g ...

  7. cmd sc命令进行服务操作

    sc 命令可以注册.删除和查询系统服务 sc可供选择的参数有很多,这里不详细描述.只介绍简单的最基本的sc使用方式. 1. sc create 创建windows服务 eg: sc \\myserve ...

  8. element-ui tree树形组件自定义实现可展开选择表格

    最近做项目遇到一个需求,表格里可以展开,可以选择,大概效果如下图: 一开始是在table组件里找方法,使用了表格的合并方法,效果是实现了,但是表格的多选每次触发时,都会执行好几次,而且没法实现一部分的 ...

  9. Android 建立AIDL的步骤

    建立AIDL服务要比建立普通的服务复杂一些,具体步骤如下: (1)在Eclipse Android工程的Java包目录中建立一个扩展名为aidl的文件.该文件的语法类似于Java代码,但会稍有不同.详 ...

  10. March 2 2017 Week 9 Thursday

    The first duty of love is to listen. 爱的首要责任是倾听. Yesterday, I read an article that says a successful ...