Spring同名bean覆盖问题

http://blog.csdn.net/ado1986/article/details/49334791


默认情况下,spring在处理同一个ApplicationContext中名称相同的bean时,分为两种情况处理:

1、如果两个bean是在同一个配置文件中,那么spring会报错。

2、如果两个bean是在不同的配置文件中,默认情况下,spring会覆盖先前的bean。

在配置文件很多时,如果在启动时,对于同名的bean加载没有异常信息,出现问题后会比较难以定位。

在spring中,处理容器的元数据信息时,默认使用DefaultListableBeanFactory类,该类中有个属性:allowBeanDefinitionOverriding,默认情况下为true,即允许重名的bean可以被覆盖。

还好,spring有办法对改属性赋值。

重写ContextLoaderListener,对于web应用,容器类型为XmlWebApplicationContext,在该类中设置allowBeanDefinitionOverriding为false,然后在spring启动时,碰到同名bean就会抛出异常。

案例如下:

[java]  view plain  copy
  1. public class TradeContextLoaderListener extends ContextLoaderListener {  
  2.     @Override  
  3.     protected void customizeContext(ServletContext servletContext,  
  4.             ConfigurableWebApplicationContext applicationContext) {  
  5.         super.customizeContext(servletContext, applicationContext);  
  6.         XmlWebApplicationContext context = (XmlWebApplicationContext) applicationContext;  
  7.         context.setAllowBeanDefinitionOverriding(false);  
  8.     }  
  9. }  

配置web.xml:

[html]  view plain  copy
  1. <listener>  
  2.     <description>spring监听器</description>  
  3.     <listener-class>com.***.trade.system.web.util.TradeContextLoaderListener</listener-class>  
  4. </listener>  

发布了66 篇原创文章 · 获赞 17 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/ligeforrent/article/details/77237030