如何在Spring Boot应用程序中覆盖DefaultListableBeanFactory?

时间:2018-07-04 15:35:28

标签: spring spring-boot

在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());
    }
}

启动应用程序时,它会显示“值2”消息,即从TestConfiguration2初始化myTempComponent bean。 如果有两个或多个候选者,我想禁止创建该bean(和其他任何bean)。

我意识到我可以通过将DefaultListableBeanFactory.allowBeanDefinitionOverriding设置为false来达到这个目标。 但是如何在Spring Boot应用程序中设置此属性?您能提供一个例子吗?

1 个答案:

答案 0 :(得分:2)

您可以设置

 private static class CustomAppCtxInitializer implements ApplicationContextInitializer<GenericApplicationContext> {

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

然后拥有

    public static void main(String[] args) {
    try {
        final SpringApplication springApplication = new SpringApplication(Application.class);
        springApplication.addInitializers(new CustomAppCtxInitializer());