MarkHuntDev
MarkHuntDev

Reputation: 311

How to override DefaultListableBeanFactory in Spring Boot application?

Are there ways to override properties of DefaultListableBeanFactory in Spring Boot application? For example, I want to set the DefaultListableBeanFactory.allowBeanDefinitionOverriding property to false.

EDIT

Use case.

I have pretty plain class:

@Data
@AllArgsConstructor
class MyTempComponent {
    private String value;
}

Which I want use as @Bean in my application but this bean can be defined several times, for example:

@Configuration
class TestConfiguration1 {
    @Bean
    MyTempComponent myTempComponent() {
        return new MyTempComponent("Value 1");
    }
}
@Configuration
class TestConfiguration2 {
    @Bean
    MyTempComponent myTempComponent() {
        return new MyTempComponent("Value 2");
    }
}

Also there is a consumer of that 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());
    }
}

When an application starts it prints "Value 2" message, i.e. initializes myTempComponent bean from TestConfiguration2. I want to prohibit creation of that bean (and any other beans) if there are two or more candidates.

As I realized I can reach this goal via setting DefaultListableBeanFactory.allowBeanDefinitionOverriding to false. But how to set this property in Spring Boot application? Could you provide an example please?

Upvotes: 2

Views: 1861

Answers (1)

anders.norgaard
anders.norgaard

Reputation: 1080

You can set

 private static class CustomAppCtxInitializer implements ApplicationContextInitializer<GenericApplicationContext> {

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

and then have

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

Upvotes: 2

Related Questions