1、在spring同一个配置文件中,不能存在id相同的两个bean,否则会报错。

2、在两个不同的spring配置文件中,可以存在id相同的两个bean,启动时,不会报错。这是因为spring ioc容器在加载bean的过程中,类DefaultListableBeanFactory会对id相同的bean进行处理:后加载的配置文件的bean,覆盖先加载的配置文件的bean。DefaultListableBeanFactory类中,有个属性allowBeanDefinitionOverriding,默认值为true,该值就是用来指定出现两个bean的id相同的情况下,如何进行处理。如果该值为false,则不会进行覆盖,而是抛出异常。

 

DefaultListableBeanFactory类有一个allowBeanDefinitionOverriding属性,其默认值为true.

只要将这个allowBeanDefinitionOverriding值在spring初始化的时候设置为false就行了

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

[xhtml] view plain copy
<listener>  
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
</listener>  
这个listener来完成的,在这个listener中会构造 org.springframework.web.context.ContextLoader 这个构造器来加载bean

所以,只要扩展 ContextLoader 和ContextLoaderListener这两个类就行了

 

public class KoubeiContextLoader extends ContextLoader {  
  
    @Override  
    protected void customizeContext(ServletContext servletContext,  
            ConfigurableWebApplicationContext applicationContext) {  
        XmlWebApplicationContext context = (XmlWebApplicationContext) applicationContext;  
        context.setAllowBeanDefinitionOverriding(false);  
    }  
  
}  
 

public class KoubeiContextLoaderListener extends ContextLoaderListener {  
  
    @Override  
    protected ContextLoader createContextLoader() {  
        return new KoubeiContextLoader();  
    }  
  
}  
 

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

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

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐