Disallow Bean Definition Overriding?

前端 未结 2 1239
一整个雨季
一整个雨季 2021-01-14 00:51

I want to disallow bean definition overriding in a SpringApplication. In other words, I want the effect of invoking GenericApplicationContext.setAllowBean

相关标签:
2条回答
  • 2021-01-14 01:07

    I have come across similar issue but not in spring boot application but in normal spring-mvc application which is having xml based configurations, so this solution might help people looking for other than spring-boot apps,

    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        beanFactory.setAllowBeanDefinitionOverriding(false);
        new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions(new ClassPathResource("spring-first.xml"));
    
    0 讨论(0)
  • 2021-01-14 01:10

    Well, you can achieve it with some Boot features and context customization:

    @EnableAutoConfiguration
    public class MyApp {
    
        public static void main(String[] args) throws InterruptedException {
            ConfigurableApplicationContext ctx = new SpringApplicationBuilder(MyApp.class)
                    .initializers(new ApplicationContextInitializer<GenericApplicationContext>() {
                        @Override
                        public void initialize(GenericApplicationContext applicationContext) {
                            applicationContext.setAllowBeanDefinitionOverriding(false);
                        }
                    }).run(args);
        }
    
    }
    

    All other info you can find from source code and JavaDocs of mentioned classes.

    0 讨论(0)
提交回复
热议问题