如何在Spring引导应用程序中重写DefaultListableBeanFactory?

如何在Spring引导应用程序中重写DefaultListableBeanFactory?,spring,spring-boot,Spring,Spring Boot,在Spring Boot应用程序中是否有方法重写DefaultListableBeanFactory的属性? 例如,我想将DefaultListableBeanFactory.allowBeanDefinitionOverriding属性设置为false 编辑 用例 我的课很简单: @Data @AllArgsConstructor class MyTempComponent { private String value; } 我希望在我的应用程序中将其用作@Bean,但可以多次定义此

在Spring Boot应用程序中是否有方法重写
DefaultListableBeanFactory
的属性? 例如,我想将
DefaultListableBeanFactory.allowBeanDefinitionOverriding
属性设置为
false

编辑

用例

我的课很简单:

@Data
@AllArgsConstructor
class MyTempComponent {
    private String value;
}
我希望在我的应用程序中将其用作@Bean,但可以多次定义此Bean,例如:

@Configuration
class TestConfiguration1 {
    @Bean
    MyTempComponent myTempComponent() {
        return new MyTempComponent("Value 1");
    }
}
@Configuration
class TestConfiguration2 {
    @Bean
    MyTempComponent myTempComponent() {
        return new MyTempComponent("Value 2");
    }
}
还有一个bean的消费者:

@Component
class TestConfiguration3 {

    private MyTempComponent myTempComponent;

    @Autowired
    public TestConfiguration3(MyTempComponent myTempComponent) {
        this.myTempComponent = myTempComponent;
    }

    @PostConstruct
    public void print() {
        System.out.println(this.myTempComponent.getValue());
    }
}
当应用程序启动时,它会打印“Value 2”消息,即从TestConfiguration2初始化myTempComponent bean。 如果有两个或更多候选项,我想禁止创建该bean(以及任何其他bean)

正如我意识到的那样,我可以通过将
DefaultListableBeanFactory.allowBeanDefinitionOverriding
设置为
false
来实现这个目标。 但如何在Spring引导应用程序中设置此属性?您能提供一个例子吗?

您可以设置

 private static class CustomAppCtxInitializer implements ApplicationContextInitializer<GenericApplicationContext> {

    @Override
    public void initialize(GenericApplicationContext applicationContext) {
        applicationContext
                .getDefaultListableBeanFactory()
                .setAllowBeanDefinitionOverriding(false);
    }
}

DefaultListableBeanFactory.setAllowBeanDefinitionOverriding(false)应该可以工作。您是否尝试在DefaultListableBeanFactory.java中查找方法,或者我遗漏了什么?我相信它应该可以工作,但如何在Spring Boot app中定义它呢?:)你能告诉我你想要实现什么吗?我想了解你的用途-case@ShaunakPatel我在问题的编辑部分添加了用例。太好了!非常感谢。
    public static void main(String[] args) {
    try {
        final SpringApplication springApplication = new SpringApplication(Application.class);
        springApplication.addInitializers(new CustomAppCtxInitializer());