-
Notifications
You must be signed in to change notification settings - Fork 38.8k
Description
This is a follow-up from the spring-boot gitter channel.
When upgrading the spring-boot bom from 2.2.5.RELEASE to 2.2.6.RELEASE I get this exception:
Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'aBean' for bean class [com.example.demo.ABean] conflicts with existing, non-compatible bean definition of same name and class [com.example.demo.ABean]
at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.checkCandidate(ClassPathBeanDefinitionScanner.java:349) ~[spring-context-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:287) ~[spring-context-5.2.5.RELEASE.jar:5.2.5.RELEASE]
The problem remains even when using 2.2.7.BUILD-SNAPSHOT.
Here's what I've discovered while debugging it:
- so what happens is that the classpath scanner detects my test configuration (which has
@ComponentScanannotation) and that adds theaBeanbean, but it also picks up theDemoApplication(the class with the main method). So it does classpath scanning for theDemoApplicationagain so theComponentScanAnnotationParserperforms the scan, and finds theaBeanagain and then calls theisCompatiblemethod here:
https://github.com/spring-projects/spring-framework/blob/master/spring-context/src/main/java/org/springframework/context/annotation/ClassPathBeanDefinitionScanner.java#L364
This method returns false so an exception is raised.
-
It is important to have the
spring-context-indexerdependency in your classpath. If you have it then the beans passed toisCompatiblemethod will getgetSource()return null. -
it is also important to name the bean
ABean. If I name itDemoBeanthen the exception does not happen - I think the component scan finds candidates sorted by beanName. So ifABeancomes beforeDemoApplicationthen it will fail if I name itDemoBeanthen it will come afterDemoApplicationand it will not fail.
Here's a repository that reproduces the problem:
https://github.com/ptahchiev/conflicting-bean