Support constructor injection for @Import classes
Allow `ImportBeanDefinitionRegistrar`, `ImportSelector`, `DeferredImportSelector.Group` and `TypeFilter` to use constructor parameters as an alternative to `*Aware` callbacks. In order to remain backwards compatible, injection only occurs when there is a single constructor with one or more parameters. The following parameter types are supported: * `Environment` * `BeanFactory` * `ClassLoader` * `ResourceLoader` In order to keep the algorithm simple, subclass parameter types are not supported. For example, you cannot use `ConfigurableEnvironment` instead of `Environment`. Closes gh-23637
This commit is contained in:
@@ -151,9 +151,9 @@ class ComponentScanAnnotationParser {
|
||||
case CUSTOM:
|
||||
Assert.isAssignable(TypeFilter.class, filterClass,
|
||||
"@ComponentScan CUSTOM type filter requires a TypeFilter implementation");
|
||||
TypeFilter filter = BeanUtils.instantiateClass(filterClass, TypeFilter.class);
|
||||
ParserStrategyUtils.invokeAwareMethods(
|
||||
filter, this.environment, this.resourceLoader, this.registry);
|
||||
|
||||
TypeFilter filter = ParserStrategyUtils.instantiateClass(filterClass, TypeFilter.class,
|
||||
this.environment, this.resourceLoader, this.registry);
|
||||
typeFilters.add(filter);
|
||||
break;
|
||||
default:
|
||||
|
||||
@@ -559,9 +559,8 @@ class ConfigurationClassParser {
|
||||
if (candidate.isAssignable(ImportSelector.class)) {
|
||||
// Candidate class is an ImportSelector -> delegate to it to determine imports
|
||||
Class<?> candidateClass = candidate.loadClass();
|
||||
ImportSelector selector = BeanUtils.instantiateClass(candidateClass, ImportSelector.class);
|
||||
ParserStrategyUtils.invokeAwareMethods(
|
||||
selector, this.environment, this.resourceLoader, this.registry);
|
||||
ImportSelector selector = ParserStrategyUtils.instantiateClass(candidateClass, ImportSelector.class,
|
||||
this.environment, this.resourceLoader, this.registry);
|
||||
if (selector instanceof DeferredImportSelector) {
|
||||
this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector);
|
||||
}
|
||||
@@ -576,9 +575,8 @@ class ConfigurationClassParser {
|
||||
// delegate to it to register additional bean definitions
|
||||
Class<?> candidateClass = candidate.loadClass();
|
||||
ImportBeanDefinitionRegistrar registrar =
|
||||
BeanUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class);
|
||||
ParserStrategyUtils.invokeAwareMethods(
|
||||
registrar, this.environment, this.resourceLoader, this.registry);
|
||||
ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class,
|
||||
this.environment, this.resourceLoader, this.registry);
|
||||
configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
|
||||
}
|
||||
else {
|
||||
@@ -822,8 +820,7 @@ class ConfigurationClassParser {
|
||||
private Group createGroup(@Nullable Class<? extends Group> type) {
|
||||
Class<? extends Group> effectiveType = (type != null ? type
|
||||
: DefaultDeferredImportSelectorGroup.class);
|
||||
Group group = BeanUtils.instantiateClass(effectiveType);
|
||||
ParserStrategyUtils.invokeAwareMethods(group,
|
||||
Group group = ParserStrategyUtils.instantiateClass(effectiveType, Group.class,
|
||||
ConfigurationClassParser.this.environment,
|
||||
ConfigurationClassParser.this.resourceLoader,
|
||||
ConfigurationClassParser.this.registry);
|
||||
|
||||
@@ -46,6 +46,7 @@ import java.lang.annotation.Target;
|
||||
* @since 3.0
|
||||
* @see Configuration
|
||||
* @see ImportSelector
|
||||
* @see ImportBeanDefinitionRegistrar
|
||||
* @see ImportResource
|
||||
*/
|
||||
@Target(ElementType.TYPE)
|
||||
|
||||
@@ -40,6 +40,15 @@ import org.springframework.core.type.AnnotationMetadata;
|
||||
* <li>{@link org.springframework.context.ResourceLoaderAware ResourceLoaderAware}
|
||||
* </ul>
|
||||
*
|
||||
* <p>Alternatively, the class may provide a single constructor with one or more of
|
||||
* the following supported parameter types:
|
||||
* <ul>
|
||||
* <li>{@link org.springframework.core.env.Environment Environment}</li>
|
||||
* <li>{@link org.springframework.beans.factory.BeanFactory BeanFactory}</li>
|
||||
* <li>{@link java.lang.ClassLoader ClassLoader}</li>
|
||||
* <li>{@link org.springframework.core.io.ResourceLoader ResourceLoader}</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>See implementations and associated unit tests for usage examples.
|
||||
*
|
||||
* @author Chris Beams
|
||||
|
||||
@@ -33,6 +33,15 @@ import org.springframework.core.type.AnnotationMetadata;
|
||||
* <li>{@link org.springframework.context.ResourceLoaderAware ResourceLoaderAware}</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Alternatively, the class may provide a single constructor with one or more of
|
||||
* the following supported parameter types:
|
||||
* <ul>
|
||||
* <li>{@link org.springframework.core.env.Environment Environment}</li>
|
||||
* <li>{@link org.springframework.beans.factory.BeanFactory BeanFactory}</li>
|
||||
* <li>{@link java.lang.ClassLoader ClassLoader}</li>
|
||||
* <li>{@link org.springframework.core.io.ResourceLoader ResourceLoader}</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>{@code ImportSelector} implementations are usually processed in the same way
|
||||
* as regular {@code @Import} annotations, however, it is also possible to defer
|
||||
* selection of imports until all {@code @Configuration} classes have been processed
|
||||
|
||||
@@ -16,6 +16,10 @@
|
||||
|
||||
package org.springframework.context.annotation;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
|
||||
import org.springframework.beans.BeanInstantiationException;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.Aware;
|
||||
import org.springframework.beans.factory.BeanClassLoaderAware;
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
@@ -26,31 +30,101 @@ import org.springframework.context.EnvironmentAware;
|
||||
import org.springframework.context.ResourceLoaderAware;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.core.io.ResourceLoader;
|
||||
import org.springframework.lang.Nullable;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Common delegate code for the handling of parser strategies, e.g.
|
||||
* {@code TypeFilter}, {@code ImportSelector}, {@code ImportBeanDefinitionRegistrar}
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @author Phillip Webb
|
||||
* @since 4.3.3
|
||||
*/
|
||||
abstract class ParserStrategyUtils {
|
||||
|
||||
/**
|
||||
* Invoke {@link BeanClassLoaderAware}, {@link BeanFactoryAware},
|
||||
* Instantiate a class using an appropriate constructor and return the new
|
||||
* instance as the specified assignable type. The returned instance will
|
||||
* have {@link BeanClassLoaderAware}, {@link BeanFactoryAware},
|
||||
* {@link EnvironmentAware}, and {@link ResourceLoaderAware} contracts
|
||||
* if implemented by the given object.
|
||||
* invoked if they are implemented by the given object.
|
||||
* @since 5.2
|
||||
*/
|
||||
public static void invokeAwareMethods(Object parserStrategyBean, Environment environment,
|
||||
ResourceLoader resourceLoader, BeanDefinitionRegistry registry) {
|
||||
@SuppressWarnings("unchecked")
|
||||
static <T> T instantiateClass(Class<?> clazz, Class<T> assignableTo,
|
||||
Environment environment, ResourceLoader resourceLoader,
|
||||
BeanDefinitionRegistry registry) {
|
||||
|
||||
Assert.notNull(clazz, "Class must not be null");
|
||||
Assert.isAssignable(assignableTo, clazz);
|
||||
if (clazz.isInterface()) {
|
||||
throw new BeanInstantiationException(clazz, "Specified class is an interface");
|
||||
}
|
||||
ClassLoader classLoader = (registry instanceof ConfigurableBeanFactory ?
|
||||
((ConfigurableBeanFactory) registry).getBeanClassLoader() : resourceLoader.getClassLoader());
|
||||
T instance = (T) createInstance(clazz, environment, resourceLoader, registry, classLoader);
|
||||
ParserStrategyUtils.invokeAwareMethods(instance, environment, resourceLoader, registry, classLoader);
|
||||
return instance;
|
||||
}
|
||||
|
||||
private static Object createInstance(Class<?> clazz, Environment environment,
|
||||
ResourceLoader resourceLoader, BeanDefinitionRegistry registry,
|
||||
@Nullable ClassLoader classLoader) {
|
||||
|
||||
Constructor<?>[] constructors = clazz.getDeclaredConstructors();
|
||||
if (constructors.length == 1 && constructors[0].getParameterCount() > 0) {
|
||||
try {
|
||||
Constructor<?> constructor = constructors[0];
|
||||
Object[] args = resolveArgs(constructor.getParameterTypes(),
|
||||
environment, resourceLoader, registry, classLoader);
|
||||
return BeanUtils.instantiateClass(constructor, args);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
throw new BeanInstantiationException(clazz, "No suitable constructor found", ex);
|
||||
}
|
||||
}
|
||||
return BeanUtils.instantiateClass(clazz);
|
||||
}
|
||||
|
||||
private static Object[] resolveArgs(Class<?>[] parameterTypes,
|
||||
Environment environment, ResourceLoader resourceLoader,
|
||||
BeanDefinitionRegistry registry, @Nullable ClassLoader classLoader) {
|
||||
|
||||
Object[] parameters = new Object[parameterTypes.length];
|
||||
for (int i = 0; i < parameterTypes.length; i++) {
|
||||
parameters[i] = resolveParameter(parameterTypes[i], environment,
|
||||
resourceLoader, registry, classLoader);
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
|
||||
private static Object resolveParameter(Class<?> parameterType,
|
||||
Environment environment, ResourceLoader resourceLoader,
|
||||
BeanDefinitionRegistry registry, @Nullable ClassLoader classLoader) {
|
||||
|
||||
if (parameterType == Environment.class) {
|
||||
return environment;
|
||||
}
|
||||
if (parameterType == ResourceLoader.class) {
|
||||
return resourceLoader;
|
||||
}
|
||||
if (parameterType == BeanFactory.class) {
|
||||
return (registry instanceof BeanFactory) ? registry : null;
|
||||
}
|
||||
if (parameterType == ClassLoader.class) {
|
||||
return classLoader;
|
||||
}
|
||||
throw new IllegalStateException(
|
||||
"Illegal method parameter type " + parameterType.getName());
|
||||
}
|
||||
|
||||
private static void invokeAwareMethods(Object parserStrategyBean, Environment environment,
|
||||
ResourceLoader resourceLoader, BeanDefinitionRegistry registry, ClassLoader classLoader) {
|
||||
|
||||
if (parserStrategyBean instanceof Aware) {
|
||||
if (parserStrategyBean instanceof BeanClassLoaderAware) {
|
||||
ClassLoader classLoader = (registry instanceof ConfigurableBeanFactory ?
|
||||
((ConfigurableBeanFactory) registry).getBeanClassLoader() : resourceLoader.getClassLoader());
|
||||
if (classLoader != null) {
|
||||
((BeanClassLoaderAware) parserStrategyBean).setBeanClassLoader(classLoader);
|
||||
}
|
||||
if (parserStrategyBean instanceof BeanClassLoaderAware && classLoader != null) {
|
||||
((BeanClassLoaderAware) parserStrategyBean).setBeanClassLoader(classLoader);
|
||||
}
|
||||
if (parserStrategyBean instanceof BeanFactoryAware && registry instanceof BeanFactory) {
|
||||
((BeanFactoryAware) parserStrategyBean).setBeanFactory((BeanFactory) registry);
|
||||
|
||||
Reference in New Issue
Block a user