Description

When registering two singleton beans using SingletonBeanRegistry#registerSingleton and using @ConditionalOnSingleCandidate(TestBean.class) a NullPointerException occurs due to the absence of corresponding bean definitions.

Reproduction Steps

Register singleton bean using SingletonBeanRegistry#registerSingleton:

   beanFactory.registerSingleton("bean1", new TestBean());
   beanFactory.registerSingleton("bean2", new TestBean());

Use @ConditionalOnSingleCandidate(TestBean.class):

@Configuration
@ConditionalOnSingleCandidate(TestBean.class)
public class TestConfiguration {
    @Bean
    public SomeBean someBean() {
        return new SomeBean();
    }
}

The application will throw a NullPointerException during startup.

Environment Information

  • Spring Boot Version: 3.5.7
  • JDK Version: 21

Comment From: linw-bai

The method org.springframework.boot.autoconfigure.condition.OnBeanCondition#getMatchingBeans does not account for cases where there is no BeanDefinition.

Caused by: java.lang.NullPointerException: null
    at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchingBeans(OnBeanCondition.java:474) ~[spring-boot-autoconfigure-3.5.7.jar:3.5.7]
    at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getPrimaryBeans(OnBeanCondition.java:464) ~[spring-boot-autoconfigure-3.5.7.jar:3.5.7]
    at org.springframework.boot.autoconfigure.condition.OnBeanCondition.evaluateConditionalOnSingleCandidate(OnBeanCondition.java:176) ~[spring-boot-autoconfigure-3.5.7.jar:3.5.7]
    at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchOutcome(OnBeanCondition.java:136) ~[spring-boot-autoconfigure-3.5.7.jar:3.5.7]
    at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:47) ~[spring-boot-autoconfigure-3.5.7.jar:3.5.7]
    ... 17 common frames omitted