问题:

当我们的web应用做成一个大项目之后,里面有很多的bean配置,如果两个bean的配置id是一样的而且实现类也是一样的,例如有下面两份xml的配置文档:

beancontext1.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "/spring-beans.dtd">
  3. <beans>
  4. <bean id="testbean" class="com.koubei.samebeannameconfict.Bean">
  5. <property name="name" value="beancontext1" />
  6. </bean>
  7. </beans>

beancontext2.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "/spring-beans.dtd">
  3. <beans>
  4. <bean id="testbean" class="com.koubei.samebeannameconfict.Bean">
  5. <property name="name" value="beancontext2" />
  6. </bean>
  7. </beans>

当spring容器初始化时候同时加载这两份配置文件到当前的上下文的时候,代码如下:

  1. public static void main(String[] args) {
  2. ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
  3. new String[] {
  4. "com/koubei/samebeannameconfict/beancontext1.xml",
  5. "com/koubei/samebeannameconfict/beancontext2.xml" });
  6. //context.setAllowBeanDefinitionOverriding(false);
  7. //context.refresh();
  8. Bean bean = (Bean) context.getBean("testbean");
  9. System.out.println(bean.getName());
  10. }

执行这个程序你会看见控制台上打印的结果是:

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 这个类中有这样一段代码:

  1. synchronized (this.beanDefinitionMap) {
  2. Object oldBeanDefinition = this.beanDefinitionMap.get(beanName);
  3. if (oldBeanDefinition != null) {
  4. if (!this.allowBeanDefinitionOverriding) {
  5. throw new BeanDefinitionStoreException(beanDefinition
  6. .getResourceDescription(), beanName,
  7. "Cannot register bean definition ["
  8. + beanDefinition + "] for bean '"
  9. + beanName + "': There is already ["
  10. + oldBeanDefinition + "] bound.");
  11. } else {
  12. if (this.logger.isInfoEnabled()) {
  13. this.logger
  14. .info("Overriding bean definition for bean '"
  15. + beanName + "': replacing ["
  16. + oldBeanDefinition + "] with ["
  17. + beanDefinition + "]");
  18. }
  19. }
  20. } else {
  21. this.beanDefinitionNames.add(beanName);
  22. this.frozenBeanDefinitionNames = null;
  23. }
  24. this.beanDefinitionMap.put(beanName, beanDefinition);
  25. resetBeanDefinition(beanName);
  26. }

spring ioc容器在加载bean的过程中会去判断beanName 是否有重复,如果发现重复的话在根据allowBeanDefinitionOverriding 这个成员变量,如果是true的话则抛出BeanDefinitionStoreException 这个异常,如果为false的话就会覆盖这个bean的定义。

所以,解决这个问题的办法就比较简单了,只要将这个allowBeanDefinitionOverriding值在spring初始化的时候设置为false就行了。

我把解决这个问题的环境放到,web工程中来:

在web工程中加载spring容器会通过:

  1. <listener>
  2. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  3. </listener>

这个listener来完成的,在这个listener中会构造 org.springframework.web.context.ContextLoader 这个构造器来加载bean

所以,只要扩展 ContextLoader 和ContextLoaderListener这两个类就行了,代码如下:

KoubeiContextLoader:

  1. import org.springframework.web.context.ConfigurableWebApplicationContext;
  2. import org.springframework.web.context.ContextLoader;
  3. import org.springframework.web.context.support.XmlWebApplicationContext;
  4. /**
  5. *
  6. *
  7. * @author 百岁(莫正华 baisui@taobao.com)
  8. * @version 1.0 2010-6-19
  9. */
  10. public class KoubeiContextLoader extends ContextLoader {
  11. @Override
  12. protected void customizeContext(ServletContext servletContext,
  13. ConfigurableWebApplicationContext applicationContext) {
  14. XmlWebApplicationContext context = (XmlWebApplicationContext) applicationContext;
  15. context.setAllowBeanDefinitionOverriding(false);
  16. }
  17. }

KoubeiContextLoaderListener:

  1. /**
  2. *
  3. *
  4. * @author 百岁(莫正华 baisui@taobao.com)
  5. * @version 1.0 2010-6-19
  6. */
  7. public class KoubeiContextLoaderListener extends ContextLoaderListener {
  8. @Override
  9. protected ContextLoader createContextLoader() {
  10. return new KoubeiContextLoader();
  11. }
  12. }

最后修改wen-inf 下web.xml 文件,修改listener的配置,如下:

  1. <listener>
  2. <listener-class>com.koubei.kac.springcontext.KoubeiContextLoaderListener</listener-class>
  3. </listener>

设置完这些就ok了,这样你项目中如果在两份被加载的xml文件中如果再出现名字相同的bean的话,spring在加载过程中就会无情的抛出异常,当你去除掉这个异常之后,就能重新出发了。yeah!!!!

最新文章

  1. hibernate缓存机制详细分析 复制代码 内部资料 请勿转载 谢谢合作
  2. ThinkCMF-smeta扩展字段
  3. vs 只能没有智能提示的解决方法
  4. stage simulator
  5. linux网络编程-(socket套接字编程UDP传输)
  6. ububtu 14.04 问题集合
  7. css3 --- 翻页动画 --- javascript --- 3d --- Action
  8. python解决SNIMissingWarning和InsecurePlatformWarning警告
  9. hdu4741
  10. POJ1789 Truck History 【最小生成树Prim】
  11. 在ubuntu linux 中编写一个自己的bash脚本
  12. android 开发设计模式---单例模式
  13. 第一个Python窗口
  14. Xamarin Essentials教程语音播报TextToSpeech
  15. boot项目swagger接口调试工具默认访问路径
  16. 深度解析 Vue 响应式原理
  17. F - New Distinct Substrings (后缀数组)
  18. MikroTik RouterOS 5.x使用HunterTik 2.3.1进行破解
  19. (转)ASCII码对照表—在线工具
  20. Linux下的Jenkins+Tomcat+Maven+Git+Shell环境的搭建使用(jenkins自动化部署)

热门文章

  1. root run-parts
  2. yii2:引用项目外的文件或类
  3. Linux:安装git
  4. 开发常用js代码段
  5. python 2 3 读写中文文件 使用codecs最方便
  6. js中关于json常用的内容、js将数字保留两位小数
  7. Flask ajax 动态html 的javascript 事件失效
  8. Struts10---拦截器
  9. sql语句遇到错误: The used SELECT statements have a different number of columns :
  10. New Concept English three (42)