diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java
index 53fb4d1d36..5f3d5f62ac 100644
--- a/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java
+++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2021 the original author or authors.
+ * Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -585,8 +585,9 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
if (!matchFound) {
// In case of FactoryBean, try to match FactoryBean instance itself next.
beanName = FACTORY_BEAN_PREFIX + beanName;
- matchFound = (includeNonSingletons || isSingleton(beanName, mbd, dbd)) && isTypeMatch(beanName, type, allowFactoryBeanInit);
-
+ if (includeNonSingletons || isSingleton(beanName, mbd, dbd)) {
+ matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
+ }
}
}
if (matchFound) {
diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java
index 00329ce7c6..ce0b36e6e4 100644
--- a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java
+++ b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java
@@ -1859,6 +1859,22 @@ class DefaultListableBeanFactoryTests {
assertBeanNamesForType(FactoryBean.class, false, false, "&factoryBean");
}
+ @Test // gh-28616
+ void getBeanNamesForTypeWithPrototypeScopedFactoryBean() {
+ FactoryBeanThatShouldntBeCalled.instantiated = false;
+ RootBeanDefinition beanDefinition = new RootBeanDefinition(FactoryBeanThatShouldntBeCalled.class);
+ beanDefinition.setScope(BeanDefinition.SCOPE_PROTOTYPE);
+ lbf.registerBeanDefinition("factoryBean", beanDefinition);
+ assertThat(FactoryBeanThatShouldntBeCalled.instantiated).isFalse();
+ assertThat(lbf.containsSingleton("factoryBean")).isFalse();
+
+ // We should not find any beans of the following types if the FactoryBean itself is prototype-scoped.
+ assertBeanNamesForType(Runnable.class, false, false);
+ assertBeanNamesForType(Callable.class, false, false);
+ assertBeanNamesForType(RepositoryFactoryInformation.class, false, false);
+ assertBeanNamesForType(FactoryBean.class, false, false);
+ }
+
/**
* Verifies that a dependency on a {@link FactoryBean} can not
* be autowired by name, as & is an illegal character in