SpringBoot - BeanDefinitionOverrideException: Invalid bean definition

I think I had the same problem with MongoDB. At least the error message looked exactly the same and I also had just one repository for the MongoDB, something like this:

public interface MyClassMongoRepository extends MongoRepository<MyClass, Long> {
}

The problem had been caused by class MyClass which had been used in another database before. Spring silently created some JpaRepository before creating the MongoRepository. Both repositories had the same name which caused the conflict.

Solution was to make a copy of MyClass, move it into the package of the MongoRepository and remove any JPA-specific annotations.


Bean overriding has to be enabled since Spring Boot 2.1,

https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.1-Release-Notes

Bean Overriding

Bean overriding has been disabled by default to prevent a bean being accidentally overridden. If you are relying on overriding, you will need to set spring.main.allow-bean-definition-overriding to true.

Set

spring.main.allow-bean-definition-overriding=true

or yml,

spring:
   main:
     allow-bean-definition-overriding: true

to enable overriding again.

Edit,

Bean Overriding is based of the name of the bean not its type. e.g.

@Bean
public ClassA class(){
   return new ClassA();
}

@Bean
public ClassB class(){
   return new ClassB();
}

Will cause this error in > 2.1, by default bean names are taken from the method name. Renaming the method or adding the name attribute to the Bean annotation will be a valid fix.


Enable bean overriding with such approach for example

@SpringBootTest(properties = "spring.main.allow-bean-definition-overriding=true")

or

@SpringBootApplication (properties = "spring.main.allow-bean-definition-overriding=true")