Browse Source

Log multiple primary bean detection in DefaultListableBeanFactory

Prior to this commit, a NoUniqueBeanDefinitionException was thrown when
multiple primary beans were detected within a given set of beans, but
nothing was logged. For use cases where the exception is handled by
infrastructure code, it may not be obvious to the developer what the
problem is.

To address that, a TRACE message is now logged whenever multiple
competing primary beans are detected in DefaultListableBeanFactory.

Closes gh-35550
pull/35587/head
Sam Brannen 3 months ago
parent
commit
1cdd56bf02
  1. 5
      spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java
  2. 4
      spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java

5
spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java

@ -2098,8 +2098,9 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto @@ -2098,8 +2098,9 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
boolean candidateLocal = containsBeanDefinition(candidateBeanName);
boolean primaryLocal = containsBeanDefinition(primaryBeanName);
if (candidateLocal == primaryLocal) {
throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(),
"more than one 'primary' bean found among candidates: " + candidates.keySet());
String message = "more than one 'primary' bean found among candidates: " + candidates.keySet();
logger.trace(message);
throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(), message);
}
else if (candidateLocal) {
primaryBeanName = candidateBeanName;

4
spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java

@ -1798,7 +1798,7 @@ class DefaultListableBeanFactoryTests { @@ -1798,7 +1798,7 @@ class DefaultListableBeanFactoryTests {
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class)
.isThrownBy(() -> lbf.getBean(TestBean.class))
.withMessageContaining("more than one 'primary'");
.withMessageEndingWith("more than one 'primary' bean found among candidates: [bd1, bd2]");
}
@Test
@ -2122,7 +2122,7 @@ class DefaultListableBeanFactoryTests { @@ -2122,7 +2122,7 @@ class DefaultListableBeanFactoryTests {
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class)
.isThrownBy(() -> lbf.getBean(ConstructorDependency.class, 42))
.withMessageContaining("more than one 'primary'");
.withMessageEndingWith("more than one 'primary' bean found among candidates: [bd1, bd2]");
}
@Test

Loading…
Cancel
Save