Skip to content

Commit c11abf4

Browse files
committed
Polish 'Allow beans without public constructors to load'
See gh-20929
1 parent d8d8f9c commit c11abf4

File tree

3 files changed

+15
-4
lines changed

3 files changed

+15
-4
lines changed

spring-boot-project/spring-boot/src/main/java/org/springframework/boot/BeanDefinitionLoader.java

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package org.springframework.boot;
1818

1919
import java.io.IOException;
20+
import java.lang.reflect.Constructor;
2021
import java.util.HashSet;
2122
import java.util.Set;
2223

@@ -41,6 +42,7 @@
4142
import org.springframework.core.type.filter.TypeFilter;
4243
import org.springframework.util.Assert;
4344
import org.springframework.util.ClassUtils;
45+
import org.springframework.util.ObjectUtils;
4446
import org.springframework.util.StringUtils;
4547

4648
/**
@@ -151,7 +153,7 @@ private int load(Class<?> source) {
151153
GroovyBeanDefinitionSource loader = BeanUtils.instantiateClass(source, GroovyBeanDefinitionSource.class);
152154
load(loader);
153155
}
154-
if (isComponent(source)) {
156+
if (isEligible(source)) {
155157
this.annotatedReader.register(source);
156158
return 1;
157159
}
@@ -277,8 +279,17 @@ private Package findPackage(CharSequence source) {
277279
* @return true if the given bean type is eligible for registration, i.e. not a groovy
278280
* closure nor an anonymous class
279281
*/
280-
private boolean isComponent(Class<?> type) {
281-
return !type.getName().matches(".*\\$_.*closure.*") && !type.isAnonymousClass();
282+
private boolean isEligible(Class<?> type) {
283+
return !(type.isAnonymousClass() || isGroovyClosure(type) || hasNoConstructors(type));
284+
}
285+
286+
private boolean isGroovyClosure(Class<?> type) {
287+
return type.getName().matches(".*\\$_.*closure.*");
288+
}
289+
290+
private boolean hasNoConstructors(Class<?> type) {
291+
Constructor<?>[] constructors = type.getDeclaredConstructors();
292+
return ObjectUtils.isEmpty(constructors);
282293
}
283294

284295
/**

spring-boot-project/spring-boot/src/test/java/org/springframework/boot/BeanDefinitionLoaderTests.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ void loadClass() {
5858
@Test
5959
void anonymousClassNotLoaded() {
6060
MyComponent myComponent = new MyComponent() {
61+
6162
};
6263
BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, myComponent.getClass());
6364
assertThat(loader.load()).isEqualTo(0);

spring-boot-project/spring-boot/src/test/java/org/springframework/boot/sampleconfig/MyNamedComponent.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
public class MyNamedComponent {
2323

2424
MyNamedComponent() {
25-
2625
}
2726

2827
}

0 commit comments

Comments
 (0)