Spring中Bean多种实现切换方案
一个公共工程中的Spring配置文件,可能会被多个工程引用。因为每个工程可能只需要公共工程中的一部分Bean,所以这些工程的Spring容器启动时,需要区分开哪些Bean要创建出来。另一种场景是:想通过Properties文件中的配置开关,就将Spring配置文件中Bean的实现切换成另一套。
方法一:Qulifier区分Bean
1.1应用实例
以Apache开源框架Jetspeed中的一段配置为例:page-manager.xml
===============================================================================
<bean name="xmlPageManager"class="org.apache.jetspeed.page.psml.CastorXmlPageManager"init-method="init" destroy-method="destroy">
<meta key="j2:cat" value="xmlPageManager orpageSerializer" />
<constructor-arg index="0">
<ref bean="IdGenerator"/>
</constructor-arg>
<constructor-arg index="1">
<refbean="xmlDocumentHandlerFactory" />
</constructor-arg>
……
</bean> <bean id="dbPageManager"class="org.apache.jetspeed.page.impl.DatabasePageManager"init-method="init" destroy-method="destroy">
<meta key="j2:cat" value="dbPageManager orpageSerializer" />
<!-- OJB configuration file resourcepath -->
<constructor-arg index="0">
<value>JETSPEED-INF/ojb/page-manager-repository.xml</value>
</constructor-arg>
<!-- fragment id generator -->
<constructor-arg index="1">
<ref bean="IdGenerator"/>
</constructor-arg>
……
</bean>
1.2 Bean过滤器
JetspeedBeanDefinitionFilter在Spring容器解析每个Bean定义时,会取出上面Bean配置中j2:cat对应的值,例如dbPageManageror pageSerializer。然后将这部分作为正则表达式与当前的Key(从配置文件中读出)进行匹配。只有匹配上的Bean,才会被Spring容器创建出来。
JetspeedBeanDefinitionFilter
===============================================================================
public boolean match(BeanDefinition bd)
{
String beanCategoriesExpression = (String)bd.getAttribute(CATEGORY_META_KEY);
boolean matched = true;
if (beanCategoriesExpression != null)
{
matched = ((matcher != null)&& matcher.match(beanCategoriesExpression));
}
return matched;
} public void registerDynamicAlias(BeanDefinitionRegistry registry, String beanName,BeanDefinition bd)
{
String aliases =(String)bd.getAttribute(ALIAS_META_KEY);
if (aliases != null)
{
StringTokenizer st = newStringTokenizer(aliases, " ,");
while (st.hasMoreTokens())
{
String alias = st.nextToken();
if (!alias.equals(beanName))
{
registry.registerAlias(beanName, alias);
}
}
}
}
===============================================================================
match()方法中的CATEGORY_META_KEY的值就是j2:cat,matcher类中保存的就是当前的Key,并负责将当前Key与每个Bean的进行正则表达式匹配。
registerDynamicAlias的作用是:在Bean匹配成功后,定制的Spring容器会调用此方法为Bean注册别名。详见下面1.3中的源码。
1.3定制Spring容器
定制一个Spring容器,重写registerBeanDefinition()方法,在Spring注册Bean时进行拦截。
===============================================================================
public class FilteringXmlWebApplicationContextextends XmlWebApplicationContext
{
private JetspeedBeanDefinitionFilterfilter; publicFilteringXmlWebApplicationContext(JetspeedBeanDefinitionFilter filter, String[]configLocations, Properties initProperties, ServletContext servletContext)
{
this(filter, configLocations,initProperties, servletContext, null);
} publicFilteringXmlWebApplicationContext(JetspeedBeanDefinitionFilter filter, String[]configLocations, Properties initProperties, ServletContext servletContext,ApplicationContext parent)
{
super();
if (parent != null)
{
this.setParent(parent);
}
if (initProperties != null)
{
PropertyPlaceholderConfigurer ppc =new PropertyPlaceholderConfigurer();
ppc.setIgnoreUnresolvablePlaceholders(true);
ppc.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_FALLBACK);
ppc.setProperties(initProperties);
addBeanFactoryPostProcessor(ppc);
}
setConfigLocations(configLocations);
setServletContext(servletContext);
this.filter = filter;
} protected DefaultListableBeanFactorycreateBeanFactory()
{
return new FilteringListableBeanFactory(filter,getInternalParentBeanFactory());
}
} public classFilteringListableBeanFactory extends DefaultListableBeanFactory
{
private JetspeedBeanDefinitionFilterfilter; public FilteringListableBeanFactory(JetspeedBeanDefinitionFilterfilter, BeanFactory parentBeanFactory)
{
super(parentBeanFactory);
this.filter = filter;
if (this.filter == null)
{
this.filter = newJetspeedBeanDefinitionFilter();
}
this.filter.init();
} /**
* Override of the registerBeanDefinitionmethod to optionally filter out a BeanDefinition and
* if requested dynamically register anbean alias
*/
public void registerBeanDefinition(StringbeanName, BeanDefinition bd)
throws BeanDefinitionStoreException
{
if (filter.match(bd))
{
super.registerBeanDefinition(beanName, bd);
if (filter != null)
{
filter.registerDynamicAlias(this, beanName, bd);
}
}
}
}
1.4为Bean起别名
使用BeanReferenceFactoryBean工厂Bean,将上面配置的两个Bean(xmlPageManager和dbPageManager)包装起来。将Key配成各自的,实现通过配置当前Key来切换两种实现。别名都配成一个,这样引用他们的Bean就直接引用这个别名就行了。例如下面的PageLayoutComponent。
page-manager.xml
===============================================================================
<bean class="org.springframework.beans.factory.config.BeanReferenceFactoryBean">
<meta key="j2:cat"value="xmlPageManager" />
<meta key="j2:alias"value="org.apache.jetspeed.page.PageManager" />
<propertyname="targetBeanName" value="xmlPageManager" />
</bean> <bean class="org.springframework.beans.factory.config.BeanReferenceFactoryBean">
<meta key="j2:cat"value="dbPageManager" />
<meta key="j2:alias"value="org.apache.jetspeed.page.PageManager" />
<propertyname="targetBeanName" value="dbPageManager" />
</bean> <bean id="org.apache.jetspeed.layout.PageLayoutComponent"
class="org.apache.jetspeed.layout.impl.PageLayoutComponentImpl">
<meta key="j2:cat"value="default" />
<constructor-arg index="0">
<refbean="org.apache.jetspeed.page.PageManager" />
</constructor-arg>
<constructor-arg index="1">
<value>jetspeed-layouts::VelocityOneColumn</value>
</constructor-arg>
</bean>
方法二:使用注解区分Bean
(未完 待续)
Spring中Bean多种实现切换方案的更多相关文章
- Spring入门(五):Spring中bean的作用域
1. Spring中bean的多种作用域 在默认情况下,Spring应用上下文中所有的bean都是以单例(singleton)的形式创建的,即不管给定的一个bean被注入到其他bean多少次,每次所注 ...
- Spring中bean的管理
Spring 中常见的容器 我们知道spring容器就是spring中bean的驻留场所.spring容器并不是只有一个.spring自带了多个容器实现,可以归为两种不同的类型:bean工厂和应用上下 ...
- Spring中Bean的作用域、生命周期
Bean的作用域.生命周期 Bean的作用域 Spring 3中为Bean定义了5中作用域,分别为singleton(单例).protot ...
- Spring中Bean的实例化
Spring中Bean的实例化 在介绍Bean的三种实例化的方式之前,我们首先需要介绍一下什么是Bean,以及Bean的配置方式. 如果 ...
- Spring中Bean的命名问题(id和name区别)及ref和idref之间的区别
Spring中Bean的命名 1.每个Bean可以有一个id属性,并可以根据该id在IoC容器中查找该Bean,该id属性值必须在IoC容器中唯一: 2.可以不指定id属性,只指定全限定类名,如: & ...
- (转)Spring中Bean的命名问题(id和name区别)及ref和idref之间的区别
Spring中Bean的命名 1.每个Bean可以有一个id属性,并可以根据该id在IoC容器中查找该Bean,该id属性值必须在IoC容器中唯一: 2.可以不指定id属性,只指定全限定类名,如: & ...
- JAVA面试题:Spring中bean的生命周期
Spring 中bean 的生命周期短暂吗? 在spring中,从BeanFactory或ApplicationContext取得的实例为Singleton,也就是预设为每一个Bean的别名只能维持一 ...
- Spring中Bean的命名问题及ref和idref之间的区别
一直在用Spring,其实对其了解甚少,刚去了解了一下Spring中Bean的命名问题以及ref和idref之间的区别,略作记录,以备后查. Spring中Bean的命名 1.每个Bean可以有一个i ...
- 深入理解Spring中bean的生命周期
[Spring中bean的生命周期] bean的生命周期 1.以ApplocationContext上下文单例模式装配bean为例,深入探讨bean的生命周期: (1).生命周期图: (2).具体事例 ...
随机推荐
- python中没有字符(char)这一基本数据类型
感觉受C语言的影响太大了,一开始以为python中也会有字符这一基本数据类型,后来遇到了很多问题,这才发现python中压根没有这一数据类型( ╯□╰ ). 吐槽一下:感觉python还真是'够简单啊 ...
- Python中模块之os的功能介绍
Python中模块之os的功能介绍 1. os的变量 path 模块路径 方法:os.path 返回值:module 例如:print(os.path) >>> <module ...
- Linux学习之CentOS(八)----文件与目录的默认权限与隐藏权限(转)
文件与目录的默认权限与隐藏权限 一个文件有若干个属性, 包括读写运行(r, w, x)等基本权限,及是否为目录 (d) 与文件 (-) 或者是连结档 (l) 等等的属性! 要修改属性的方法在前面也约略 ...
- 判断是否是IE;自定义onkeyup事件
<script> /*onkeyup和onchange事件在IE下冲突,在此做区分*/ if (!!window.ActiveXObject || "ActiveXObject& ...
- git报错:'fatal:remote origin already exists'怎么处理?附上git常用操作以及说明。
git添加远程库的时候有可能出现如下的错误, 怎么解决? 只要两步: 1.先删除 $ git remote rm origin 2.再次执行添加就可以了. ---------------------- ...
- SQL执行SQL语句提示 "内存不足"(insufficient memory....)的解决方法
由于本地执行的sql script的文件太大但是本地sql的运行内存有限,当我在MSSql的工具上运行这份178M左右的脚本的时候 它会提示 如下错误(Insufficient memory to c ...
- Ubuntu14.04和Windows双系统时无法挂载磁盘解决方法
基本状况:我电脑Ubuntu14.04 和 Windows10 双系统,一个固态磁盘,一个机械磁盘.Ubuntu14.04装固态里面了,固态里没有Windows内容. 问题:Ubuntu14.04系统 ...
- Spring-cloud(六) Hystrix入门
前提 一个可用的Eureka注册中心(文中以之前博客中双节点注册中心,不重要) 一个连接到这个注册中心的服务提供者 快速入门 项目搭建 搭建一个新maven项目,artifactid为Ribbon-c ...
- Python中切片的工作原理
切片时的索引是在两个字符之间.左边第一个字符的索引为 0,而长度为 n 的字符串其最后一个字符的右界索引为n. 例如: +---+---+---+---+---+---+ | P | y | t | ...
- ACM Least Common Multiple
The least common multiple (LCM) of a set of positive integers is the smallest positive integer which ...