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就会抛出异常。
案例如下:
- public class TradeContextLoaderListener extends ContextLoaderListener {
- @Override
- protected void customizeContext(ServletContext servletContext,
- ConfigurableWebApplicationContext applicationContext) {
- super.customizeContext(servletContext, applicationContext);
- XmlWebApplicationContext context = (XmlWebApplicationContext) applicationContext;
- context.setAllowBeanDefinitionOverriding(false);
- }
- }
配置web.xml:
- <listener>
- <description>spring监听器</description>
- <listener-class>com.***.trade.system.web.util.TradeContextLoaderListener</listener-class>
- </listener>