How to do conditional auto-wiring in Spring?
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.
BeanFactoryPostProcessor
s can read and alter bean definitions (e.g. property placeholder ${}
resolution is implemented this way).
BeanPostProcessor
s 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
@Conditional
annotation. 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?的更多相关文章
- Wiring in Spring: @Autowired, @Resource and @Inject 区别
refer:https://www.baeldung.com/spring-annotations-resource-inject-autowire 主要是查找顺序不一致: @Resource Mat ...
- 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 ...
- spring学习总结——高级装配学习一(profile与@Conditional)
前言: 在上一章装配Bean中,我们看到了一些最为核心的bean装配技术.你可能会发现上一章学到的知识有很大的用处.但是,bean装配所涉及的领域并不仅仅局限于上一章 所学习到的内容.Spring提供 ...
- Spring Framework 条件装配 之 @Conditional
Spring Framework 条件装配 之 @Conditional 前言 了解SpringBoot的小伙伴对Conditional注解一定不会陌生,在SpringBoot项目中,Conditio ...
- Spring Autowiring by AutoDetect
In Spring, "Autowiring by AutoDetect", means chooses "autowire by constructor" i ...
- Spring Autowiring by Constructor
In Spring, "Autowiring by Constructor" is actually autowiring by Type in constructor argum ...
- Spring Autowiring by Name
In Spring, "Autowiring by Name" means, if the name of a bean is same as the name of other ...
- Spring Autowiring by Type
In Spring, "Autowiring by Type" means, if data type of a bean is compatible with the data ...
- Spring Auto-Wiring Beans
In Spring framework, you can wire beans automatically with auto-wiring feature. To enable it, just d ...
- Spring boot 配置文件详解 (properties 和yml )
从其他框架来看 我们都有自己的配置文件, hibernate有hbm,mybatis 有properties, 同样, Spring boot 也有全局配置文件. Springboot使用一个全局的配 ...
随机推荐
- linux服务器查看tcp链接shell
netstat -nt |awk '{++S[$NF]} END {for (a in S ) print a,S[a]}'
- 配置文件——节点<machineKey>的作用,强随机生成
<machineKey>这个节允许你设置用于加密数据和创建数字签名的服务器特定的密钥.ASP.NET自动使用它来保护表单验证Cookie,你也可以将它用于受保护的视图状态数据.同时,这个密 ...
- C#操作xml SelectNodes,SelectSingleNode总是返回NULL
SelectNodes,SelectSingleNode总是返回NULL 原文地址:http://www.cnblogs.com/linlf03/archive/2011/11/30/2268705. ...
- sparkStreaming消费kafka-0.8方式:direct方式(存储offset到zookeeper)
生产中,为了保证kafka的offset的安全性,并且防止丢失数据现象,会手动维护偏移量(offset) 版本:kafka:0.8 其中需要注意的点: 1:获取zookeeper记录的分区偏移量 2: ...
- java生成二维码并融合模板工具类
二维码融合模板 二维码融合图片 import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.Image; i ...
- 数仓1.4 |业务数仓搭建| 拉链表| Presto
电商业务及数据结构 SKU库存量,剩余多少SPU商品聚集的最小单位,,,这类商品的抽象,提取公共的内容 订单表:周期性状态变化(order_info) id 订单编号 total_amount 订单金 ...
- Hudson与Jenkins
Hudson是Jenkins的前身,它们都是基于Java开发的一种持续集成工具,用于监控程序重复的工作,包括: 1.持续的软件版本发布/测试项目. 2.监控外部调用执行的工作. Hudson的特性 1 ...
- Dubbo入门---搭建一个最简单的Demo框架(转)
Dubbo背景和简介 Dubbo开始于电商系统,因此在这里先从电商系统的演变讲起. 单一应用框架(ORM) 当网站流量很小时,只需一个应用,将所有功能如下单支付等都部署在一起,以减少部署节点和成本. ...
- Intellij IDEA实现SpringBoot项目多端口启动
前言 有时候使用springboot项目时遇到这样一种情况,用一个项目需要复制很多遍进行测试,除了端口号不同以外,没有任何不同.这时我们强大的Intellij IDEA就能替我们实现. 实现方法 第一 ...
- SpringBoot邮件发送
这篇文章介绍springboot的邮件发送. 由于很简单就没有分出server和imp之类,只是在controller简单写个方法进行测试. 首先pom文件加入spring-boot-starter- ...