解决spring中不同配置文件中存在name或者id相同的bean可能引起的问题

    xiaoxiao2021-04-13  43

    spring对同一配置文件中相同id或者name的两个或以上的bean时,做直接抛异常的处理,而对不同配置文件中相同id或者名称的bean,只会在打印日志级别为info的信息,信息内容大概为"Overriding bean definition for bean xxx : replacing xxx with beanDefinition ". 可能引发的问题: 当不同文件中配置了相同id或者name的同一类型的两个bean时,如果这两个bean的类型虽然相同,但配置时又有差别时,如: [html]  view plain  copy <bean name="a" class="com.zyr.A">    <property name="age" value="20" />   </bean>   <bean name="a" class="com.zyr.A">    <property name="age" value="20" />   </bean>   那么最终spring容器只会实例化后面的这个bean,后者将前者覆盖了。这种情况下,要排查问题很困难。 那么如何解决这个问题呢?靠程序员自律?绝对不定义重复名称的bean?我觉得这个是非常不靠谱的,因为项目依赖可能比较复杂,开发人员不尽相同.所以我认为只有通过在程序中引入一种报错机制才能解决这个问题。 上次在调试spring源代码时,无意中发现DefaultListableBeanFactory类有一个allowBeanDefinitionOverriding属性,其默认值为true.如: [java]  view plain  copy /** Whether to allow re-registration of a different definition with the same name */   private boolean allowBeanDefinitionOverriding = true;         //allowBeanDefinitionOverriding属性在下面代码中起作用:   synchronized (this.beanDefinitionMap) {    Object oldBeanDefinition = this.beanDefinitionMap.get(beanName);    if (oldBeanDefinition != null) {     if (!this.allowBeanDefinitionOverriding) {      throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,        "Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +        "': There is already [" + oldBeanDefinition + "] bound.");     }     else {      if (this.logger.isInfoEnabled()) {       this.logger.info("Overriding bean definition for bean '" + beanName +         "': replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]");      }     }    }    else {     this.beanDefinitionNames.add(beanName);     this.frozenBeanDefinitionNames = null;    }    this.beanDefinitionMap.put(beanName, beanDefinition);   }   想到只要将其值更改为false时就可能可以解决上面的问题,即存在id或者name相同的bean时,不是打印出相关信息,而是直接抛异常,这样就可以迫使开发人员必须解决id或者name重复的问题后才能成功启动容器。然后就尝试了下, 最终找到了两个解决方案: 方案1: 1.自己写一个继承ContextLoaderListener的listener,比如SpringContextLoaderListener,然后重写方法customizeContext,如: [java]  view plain  copy public class SpringContextLoaderListener extends ContextLoaderListener {        @Override    protected void customizeContext(ServletContext servletContext, ConfigurableWebApplicationContext applicationContext) {     super.customizeContext(servletContext, applicationContext);          XmlWebApplicationContext context = (XmlWebApplicationContext) applicationContext;     context.setAllowBeanDefinitionOverriding(false); //在这里将XmlWebApplicationContext属性allowBeanDefinitionOverriding设置为false,这个属性的值最终     //会传递给DefaultListableBeanFactory类的allowBeanDefinitionOverriding属性    }   }   2.在web.xml使用自定义的listener,配置如下: [html]  view plain  copy <listener>         <listener-class>com.zyr.web.spring.SpringContextLoaderListener</listener-class>   </listener>   这样,在项目启动时,不同配置文件中如果有同名id或者name的bean,直接抛异常,容器停止启动. 但后来一想,这个方案不够好,感觉有点投机取巧。然后再想了下,想到spring既然提供了allowBeanDefinitionOverriding这个属性,理论上应该会提供方法让使用者用配置来更改其默认值的,确实如此,最终就有了方案2 . 方案2: 在org.springframework.web.context.ContextLoader类中找到了CONTEXT_INITIALIZER_CLASSES_PARAM常量,该常量可用于配置spring上下文相关全局特性,该常量在如下代码中起作用: [java]  view plain  copy protected List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>>     determineContextInitializerClasses(ServletContext servletContext) {          List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> classes =      new ArrayList<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>>();            .........          String localClassNames = servletContext.getInitParameter(CONTEXT_INITIALIZER_CLASSES_PARAM);    if (localClassNames != null) {     for (String className : StringUtils.tokenizeToStringArray(localClassNames, INIT_PARAM_DELIMITERS)) {      classes.add(loadInitializerClass(className));     }    }          return classes;   }   所以我们要做的有2步: 1.创建一个实现接口ApplicationContextInitializer的类,如SpringApplicationContextInitializer,代码如下: [java]  view plain  copy public class SpringApplicationContextInitializer implements ApplicationContextInitializer<XmlWebApplicationContext> {          public void initialize(XmlWebApplicationContext applicationContext) {     applicationContext.setAllowBeanDefinitionOverriding(false);//在这里将XmlWebApplicationContext属性allowBeanDefinitionOverriding设置为false,这个属     //性的值最终会传递给DefaultListableBeanFactory类的allowBeanDefinitionOverriding属性    }   }   2.web.xml中的增加的配置如下:   [html]  view plain  copy <context-param>           <param-name>contextInitializerClasses</param-name>           <param-value>com.zyr.web.spring.SpringApplicationContextInitializer</param-value>    </context-param>   但到这里,如果项目在前端使用的是spring mvc时,问题还只解决了一半,即spring根容器(相对使用spring mvc来说)如果存在同名id或者name时,容器报错停止启动.而spring mvc 的容器是作为子容器来初始化的,所以上述方案2只解决了spring根容器同名id或者name的问题,并没有解决spring mvc子容器的同名id或者name问题。 经查看源代码,最终有了方案3. 方案3: 在web.xml文件中的dispatcherServlet配置中增加如下部分配置 [html]  view plain  copy <servlet>    <servlet-name>dispatcherServlet</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <init-param>     <param-name>contextConfigLocation</param-name>     <param-value>classpath:spring/spring-mvc.xml</param-value>    </init-param>    <!-- 增加如下配置 -->    <init-param>      <param-name>contextInitializerClasses</param-name>     <param-value>com.zyr.web.spring.SpringApplicationContextInitializer</param-value> <!--这个类与方案2中的是一个类 -->    </init-param>    <load-on-startup>1</load-on-startup>   </servlet>   写了个简单测试项目,放在github上:https://github.com/zgmzyr/sameIdOrNameForBeanInSpringTest.git  引申开来:上述解决方案虽然说是为了解决重名id或者name问题而得出的,但完全可用于以后我们如果要改变spring容器的其它全局行为时,也可以用方案2解决,只不过最终改变属性值不同而已。
    转载请注明原文地址: https://ju.6miu.com/read-668592.html

    最新回复(0)