How to stop overiding a bean in Spring

前端 未结 2 394
失恋的感觉
失恋的感觉 2021-01-19 22:21

I noticed that if you define a bean with same id in two xml files, it would be overiden in the second file.

Say in file a.xml i have
       

        
相关标签:
2条回答
  • 2021-01-19 22:50

    You can disable the feature to disallow beanoverriding by calling the setAllowBeanDefinitionOverriding and pass false. This has to be done early on before anything is loaded. You would either need to create your own custom ContextLoader for this or (if you are on Spring 3.1 or up) you can create an ApplicationContextInitializer and register this in your web.xml.

    public class OverrideDisablingApplicationContextInitializer implements ApplicationContextInitializer {
    
        public void void initialize(<? extends ConfigurableApplicationContext> applicationContext);
            if (applicationContext instanceof AbstractRefreshableApplicationContext) {
                 (AbstractRefreshableApplicationContext (applicationContext)).setAllowBeanDefinitionOverriding(false);
            }
    
    }
    

    in your web.xml add the following (for the ContextLoaderListener use an init-param for the DispatcherServlet when needed)

    <context-param>
        <param-name>contextInitializerClasses</param-name>
        <param-value>your.package.here.OverrideDisablingApplicationContextInitializer<param-value>
    </context-param>
    

    From the top of my head this should disable the overriding behavior. If you use springs WebApplicationInitializer it is even easier as you are probably constructing the ApplicationContext yourself, you can then simply call the method directly and no ApplicationContextInitializer is needed.

    Links

    1. ApplicationContextInitializer javadoc
    2. AbstractRefreshableApplicationContext.setAllowBeanDefinitionOverriding javadoc
    0 讨论(0)
  • 2021-01-19 23:05

    Also:

      final ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext();
      ctx.setAllowBeanDefinitionOverriding(false);
      ctx.setConfigLocations(shardContextImport);
      ctx.setParent(refreshedEvent.getApplicationContext());
      ctx.refresh();
    
    0 讨论(0)
提交回复
热议问题