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>  

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值