Skip to content

Commit

Permalink
Polish 'Allow beans without public constructors to load'
Browse files Browse the repository at this point in the history
  • Loading branch information
philwebb committed Jun 6, 2020
1 parent d8d8f9c commit c11abf4
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package org.springframework.boot;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.HashSet;
import java.util.Set;

Expand All @@ -41,6 +42,7 @@
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
Expand Down Expand Up @@ -151,7 +153,7 @@ private int load(Class<?> source) {
GroovyBeanDefinitionSource loader = BeanUtils.instantiateClass(source, GroovyBeanDefinitionSource.class);
load(loader);
}
if (isComponent(source)) {
if (isEligible(source)) {
this.annotatedReader.register(source);
return 1;
}
Expand Down Expand Up @@ -277,8 +279,17 @@ private Package findPackage(CharSequence source) {
* @return true if the given bean type is eligible for registration, i.e. not a groovy
* closure nor an anonymous class
*/
private boolean isComponent(Class<?> type) {
return !type.getName().matches(".*\\$_.*closure.*") && !type.isAnonymousClass();
private boolean isEligible(Class<?> type) {
return !(type.isAnonymousClass() || isGroovyClosure(type) || hasNoConstructors(type));
}

private boolean isGroovyClosure(Class<?> type) {
return type.getName().matches(".*\\$_.*closure.*");
}

private boolean hasNoConstructors(Class<?> type) {
Constructor<?>[] constructors = type.getDeclaredConstructors();
return ObjectUtils.isEmpty(constructors);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ void loadClass() {
@Test
void anonymousClassNotLoaded() {
MyComponent myComponent = new MyComponent() {

};
BeanDefinitionLoader loader = new BeanDefinitionLoader(this.registry, myComponent.getClass());
assertThat(loader.load()).isEqualTo(0);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
public class MyNamedComponent {

MyNamedComponent() {

}

}

0 comments on commit c11abf4

Please sign in to comment.