Spring Boot "bean ... could not be registered ... overriding is disabled" in CI
Since Spring Boot 2.1 bean overriding is off by default. When two definitions share a name, the container throws a BeanDefinitionOverrideException instead of silently replacing one. This often surfaces in tests that add a duplicate bean.
What this error means
Startup or a test fails with "The bean 'X', defined in ..., could not be registered. A bean with that name has already been defined ... and overriding is disabled".
org.springframework.beans.factory.support.BeanDefinitionOverrideException:
Invalid bean definition with name 'clock' defined in ...: Cannot register bean
definition ... there is already ... overriding is disabled.Common causes
A test config redefines an existing bean
A @TestConfiguration or @Configuration declares a bean whose name already exists in the main context.
Two configurations declare the same bean name
Two @Bean methods (or a component and a config) produce the same name, which used to be silently overridden.
How to fix it
Prefer replacing the bean cleanly
- In tests, use
@MockBean/@SpyBean, which replace the existing bean without a name clash. - Or give the test bean a distinct name and inject by qualifier.
- Re-run so no duplicate definition exists.
@MockBean Clock clock;Allow overriding only where intended
If an intentional override is needed, enable it explicitly (scope it to tests).
spring.main.allow-bean-definition-overriding=trueHow to prevent it
- Use
@MockBean/@SpyBeanin tests instead of redefining beans. - Keep bean names unique across configurations.
- Enable overriding narrowly (test profile) rather than globally.