Spring boot 2.1 bean override vs. Primary

spring.main.allow-bean-definition-overriding=true can be placed in test configurations. If you need extensive integration testing, you will need to override beans at some point. It’s inevitable.

Though the correct answer has already been provided, it implies that your bean will have different names. So, technically, it’s not an override.

If you need a real override (because you use @Qualifiers, @Resources or something similar), since Spring Boot 2.X is only possible using the spring.main.allow-bean-definition-overriding=true property.

Update:
Be careful with Kotlin Bean Definition DSL. In Spring Boot it will require a custom ApplicationContextInitializer, like so:

class BeansInitializer : ApplicationContextInitializer<GenericApplicationContext> {

    override fun initialize(context: GenericApplicationContext) =
            beans.initialize(context)

}

Now if you decide to override one of such DSL-based beans in your test via @Primary @Bean method, it will not do. The initializer will kick in after @Bean methods and you’d still get the initial, DSL-based bean in your tests even with @Primary on the test @Bean.
One other option would be to also create a test initializer for your tests and list them all in your test properties, like so(order matters):

context:
    initializer:
        classes: com.yuranos.BeansInitializer, com.yuranos.TestBeansInitializer

Bean Definition DSL also supports primary property via:

bean(isPrimary=true) {...}

– which you’ll need to eliminate ambiguity when you try to inject a bean, however main:allow-bean-definition-overriding: true is not needed if you go pure DSL way.

(Spring Boot 2.1.3)

Leave a Comment