spring bean id重复覆盖的问题解决
问题:
当我们的web应用做成一个大项目之后,里面有很多的bean配置,如果两个bean的配置id是一样的而且实现类也是一样的,例如有下面两份xml的配置文档:
beancontext1.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "/spring-beans.dtd">
- <beans>
- <bean id="testbean" class="com.koubei.samebeannameconfict.Bean">
- <property name="name" value="beancontext1" />
- </bean>
- </beans>
beancontext2.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "/spring-beans.dtd">
- <beans>
- <bean id="testbean" class="com.koubei.samebeannameconfict.Bean">
- <property name="name" value="beancontext2" />
- </bean>
- </beans>
当spring容器初始化时候同时加载这两份配置文件到当前的上下文的时候,代码如下:
- public static void main(String[] args) {
- ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
- new String[] {
- "com/koubei/samebeannameconfict/beancontext1.xml",
- "com/koubei/samebeannameconfict/beancontext2.xml" });
- //context.setAllowBeanDefinitionOverriding(false);
- //context.refresh();
- Bean bean = (Bean) context.getBean("testbean");
- System.out.println(bean.getName());
- }
执行这个程序你会看见控制台上打印的结果是:
beancontext2
显然,beancontext2.xml的bean的配置覆盖了 beancontext1.xml中bean的配置,而且在spring初始化上下文的过程中这个过程是静悄悄的执行的,连一点警告都没有。这样如果你的项目中定义了两个id同名的bean,并且,他们的实现方式又是不一样的,这样在后期在项目中执行的逻辑看起来就会非常诡异,而且,如果有大量配置spring配置文件的话,排查问题就会非常麻烦。
解决问题:
那么,我们如何来解决这个问题吗?靠程序员自律?绝对不定义重复名称的bean?我觉得这个是不靠谱的,只有通过在程序中引入一种交错机制才能解决这个问题。
首先,我们将上面那段程序的log4j日志打开,看看在spring在初始化的时候面对有两个同名的bean是怎么处理的。
- INFO - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@aa9835: display name [org.springframework.context.support.ClassPathXmlApplicationContext@aa9835]; startup date [Sat Jun 19 18:23:30 CST 2010]; root of context hierarchy
- INFO - Loading XML bean definitions from class path resource [com/koubei/samebeannameconfict/beancontext1.xml]
- DEBUG - Using JAXP provider [com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl]
- DEBUG - Found beans DTD [file:///spring-beans.dtd] in classpath: spring-beans.dtd
- DEBUG - Loading bean definitions
- DEBUG - Loaded 1 bean definitions from location pattern [com/koubei/samebeannameconfict/beancontext1.xml]
- INFO - Loading XML bean definitions from class path resource [com/koubei/samebeannameconfict/beancontext2.xml]
- DEBUG - Using JAXP provider [com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl]
- DEBUG - Found beans DTD [file:///spring-beans.dtd] in classpath: spring-beans.dtd
- DEBUG - Loading bean definitions
- INFO - Overriding bean definition for bean 'testbean': replacing [Generic bean: class [com.koubei.samebeannameconfict.Bean]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [com/koubei/samebeannameconfict/beancontext1.xml]] with [Generic bean: class [com.koubei.samebeannameconfict.Bean]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [com/koubei/samebeannameconfict/beancontext2.xml]]
- DEBUG - Loaded 0 bean definitions from location pattern [com/koubei/samebeannameconfict/beancontext2.xml]
- INFO - Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@aa9835]:org.springframework.beans.factory.support.DefaultListableBeanFactory@1662dc8
- DEBUG - 1 beans defined in org.springframework.context.support.ClassPathXmlApplicationContext@aa9835: display name [org.springframework.context.support.ClassPathXmlApplicationContext@aa9835]; startup date [Sat Jun 19 18:23:30 CST 2010]; root of context hierarchy
- DEBUG - Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@1cb25f1]
- DEBUG - Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@503429]
- INFO - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1662dc8: defining beans [testbean]; root of factory hierarchy
- DEBUG - Creating shared instance of singleton bean 'testbean'
- DEBUG - Creating instance of bean 'testbean'
- DEBUG - Eagerly caching bean 'testbean' to allow for resolving potential circular references
- DEBUG - Finished creating instance of bean 'testbean'
- DEBUG - Returning cached instance of singleton bean 'testbean'
以上日志中标红的是关键,spring在处理有重名的bean的定义的时候原来是使用的覆盖(override)的方式。我们来看看它是如何覆盖的
在org.springframework.beans.factory.support.DefaultListableBeanFactory 这个类中有这样一段代码:
- synchronized (this.beanDefinitionMap) {
- Object oldBeanDefinition = this.beanDefinitionMap.get(beanName);
- if (oldBeanDefinition != null) {
- if (!this.allowBeanDefinitionOverriding) {
- throw new BeanDefinitionStoreException(beanDefinition
- .getResourceDescription(), beanName,
- "Cannot register bean definition ["
- + beanDefinition + "] for bean '"
- + beanName + "': There is already ["
- + oldBeanDefinition + "] bound.");
- } else {
- if (this.logger.isInfoEnabled()) {
- this.logger
- .info("Overriding bean definition for bean '"
- + beanName + "': replacing ["
- + oldBeanDefinition + "] with ["
- + beanDefinition + "]");
- }
- }
- } else {
- this.beanDefinitionNames.add(beanName);
- this.frozenBeanDefinitionNames = null;
- }
- this.beanDefinitionMap.put(beanName, beanDefinition);
- resetBeanDefinition(beanName);
- }
spring ioc容器在加载bean的过程中会去判断beanName 是否有重复,如果发现重复的话在根据allowBeanDefinitionOverriding 这个成员变量,如果是true的话则抛出BeanDefinitionStoreException 这个异常,如果为false的话就会覆盖这个bean的定义。
所以,解决这个问题的办法就比较简单了,只要将这个allowBeanDefinitionOverriding值在spring初始化的时候设置为false就行了。
我把解决这个问题的环境放到,web工程中来:
在web工程中加载spring容器会通过:
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
这个listener来完成的,在这个listener中会构造 org.springframework.web.context.ContextLoader 这个构造器来加载bean
所以,只要扩展 ContextLoader 和ContextLoaderListener这两个类就行了,代码如下:
KoubeiContextLoader:
- import org.springframework.web.context.ConfigurableWebApplicationContext;
- import org.springframework.web.context.ContextLoader;
- import org.springframework.web.context.support.XmlWebApplicationContext;
- /**
- *
- *
- * @author 百岁(莫正华 baisui@taobao.com)
- * @version 1.0 2010-6-19
- */
- public class KoubeiContextLoader extends ContextLoader {
- @Override
- protected void customizeContext(ServletContext servletContext,
- ConfigurableWebApplicationContext applicationContext) {
- XmlWebApplicationContext context = (XmlWebApplicationContext) applicationContext;
- context.setAllowBeanDefinitionOverriding(false);
- }
- }
KoubeiContextLoaderListener:
- /**
- *
- *
- * @author 百岁(莫正华 baisui@taobao.com)
- * @version 1.0 2010-6-19
- */
- public class KoubeiContextLoaderListener extends ContextLoaderListener {
- @Override
- protected ContextLoader createContextLoader() {
- return new KoubeiContextLoader();
- }
- }
最后修改wen-inf 下web.xml 文件,修改listener的配置,如下:
- <listener>
- <listener-class>com.koubei.kac.springcontext.KoubeiContextLoaderListener</listener-class>
- </listener>
设置完这些就ok了,这样你项目中如果在两份被加载的xml文件中如果再出现名字相同的bean的话,spring在加载过程中就会无情的抛出异常,当你去除掉这个异常之后,就能重新出发了。yeah!!!!
spring bean id重复覆盖的问题解决的更多相关文章
- Duplicate spring bean id
问题背景:从本地调用服务器的dubbo接口进行测试 实现思路:基于IDEA+Spring+maven+Dubbo搭建测试项目,从本地直接调用 具体实现思路可参考博客:https://www.cnb ...
- dubbo spring bean id冲突
service-security-provider应用有provider和consumer配置文件 其中secutrity-consumer引用两个服务 <dubbo:reference int ...
- spring bean id和bean name的区别
今天在分析问题时发现一个大家平时都不太注意的spring 配置问题,发出来分享下: 首先澄清一个概念: 同名bean:多个bean 有相同的 name 或者 id,称之为同名bean <bean ...
- Dubbo配置引发的一个问题--- Duplicate spring bean id
1.原因 因项目业务需要,要调用RPC框架,项目原本已经依赖了很多RPC接口需要启动时加载,所以准备做成启动时不预加载. 就是在配置的时候加上check=false. 官方文档解释的作用,就是Dubb ...
- 【Spring】Spring bean中id和name的差异
id和name都是spring 容器中中bean 的唯一标识符. id: 一个bean的唯一标识 , 命名格式必须符合XML ID属性的命名规范 name: 可以用特殊字符,并且一个bean可以用多个 ...
- spring bean的创建过程
spring的核心容器包括:core.beans.context.express language四个模块.所以对于一个简单的spring工程,最基本的就是依赖以下三个jar包即可: <depe ...
- Spring JMX之一:使用JMX管理Spring Bean
spring中关于jmx包括几个概念: MBeanExporter: 从字面上很容易理解, 用来将一些spring的bean作为MBean暴露给MBEanServer.MBeanServerFacto ...
- Spring学习(九)-----Spring bean配置继承
在 Spring,继承是用为支持bean设置一个 bean 来分享共同的值,属性或配置. 一个子 bean 或继承的bean可以继承其父 bean 的配置,属性和一些属性.另外,子 Bean 允许覆盖 ...
- Spring bean配置继承
在 Spring,继承是用为支持bean设置一个 bean 来分享共同的值,属性或配置. 一个子 bean 或继承的bean可以继承其父 bean 的配置,属性和一些属性.另外,子 Bean 允许覆盖 ...
随机推荐
- scala学习手记37 - 容器的使用
这次统一看一下scala中容器类的几个方法. Set filter()方法 filter()方法用来从Set中过滤获取含有指定特征的元素.示例代码如下: val colors1 = Set(" ...
- st表模板
http://blog.csdn.net/insistgogo/article/details/9929103 这篇博客讲解的很详细了,求区间最大值也可以用st表,时间复杂度O(n log(n)),查 ...
- 【lightoj-1055】Going Together(BFS)
链接:http://www.lightoj.com/volume_showproblem.php?problem=1055 类似推箱子的游戏,一条命令可以让abc三个小人同时移动,但是出界或者撞墙是不 ...
- shell编程实例1
1.vim hello.sh 2. #!bin/bash echo "hello world!" 3.chmod +x hello.sh 4.source hello.sh ls ...
- Node多进程相关
现状: 目前使用child_process.fork实现多进程,一个center.js负责任务分配及相关状态管理,一个worker.js负责任务执行. center.js结构: 1) 一个task_q ...
- 【tensorflow:Google】四、深层神经网络
一.深度学习与深层神经网络 1.线性模型局限性 线性模型无论多少层,表达能力是一致的.可以通过激活函数实现非线性. 2.多层网络可以解决异或运算 二.损失函数定义 1.经典损失函数: 分类问题: 二分 ...
- Linux系统下的shutdown命令用于安全的关闭/重启计算机
Linux系统下的shutdown命令用于安全的关闭/重启计算机,它不仅可以方便的实现定时关机,还可以由用户决定关机时的相关参数.在执行shutdown命令时,系统会给每个终端(用户)发送一条屏显,提 ...
- [置顶]
个人博客上线!欢迎来访~ http://onlyloveyd.cn/
简介 Hexo + Github + 个人域名 构建静态博客系统. 构建方法 参考 https://yq.aliyun.com/articles/64953 个人博客网站 Cherish Androi ...
- B. Clique Problem(贪心)
题目链接: B. Clique Problem time limit per test 2 seconds memory limit per test 256 megabytes input stan ...
- 如何用 php 读取一个很大的 excel 文件。
这个程序是用php 读取一个很大的excel文件, 先将 excel 文件保存成csv 文件, 然后利用 迭代器 逐行读取 excel 单元格的值, 拿到值以后 做相应处理,并打印结果. <?p ...