Spring源码【12】IOC容器(三)

151 阅读9分钟

1.5 IOC容器其他基础接口

1.5.1 Ordered

org.springframework.core.Ordered实现排序逻辑,实现如下:

public interface Ordered {
    // 最高优先级
    int HIGHEST_PRECEDENCE = Integer.MIN_VALUE;

    // 最低优先级
    int LOWEST_PRECEDENCE = Integer.MAX_VALUE;

    int getOrder();
}

实现Ordered的子类如下:

StaticMethodMatcherPointcutAdvisor (org.springframework.aop.support)
ScriptFactoryPostProcessor (org.springframework.scripting.support)
TransactionalApplicationListener (org.springframework.transaction.event)
    TransactionalApplicationListenerMethodAdapter (org.springframework.transaction.event)
    TransactionalApplicationListenerAdapter (org.springframework.transaction.event)
TransactionSynchronizationAdapter (org.springframework.transaction.support)
ScheduledAnnotationBeanPostProcessor (org.springframework.scheduling.annotation)
ProxyProcessorSupport (org.springframework.aop.framework)
    AbstractAdvisingBeanPostProcessor (org.springframework.aop.framework)
    AbstractAutoProxyCreator (org.springframework.aop.framework.autoproxy)
TransactionalApplicationListenerAdapter (org.springframework.transaction.event)
AspectInstanceFactory (org.springframework.aop.aspectj)
    MetadataAwareAspectInstanceFactory (org.springframework.aop.aspectj.annotation)
    SingletonAspectInstanceFactory (org.springframework.aop.aspectj)
    SimpleBeanFactoryAwareAspectInstanceFactory (org.springframework.aop.config)
    SimpleAspectInstanceFactory (org.springframework.aop.aspectj)
SourceClass in ConfigurationClassParser (org.springframework.context.annotation)
CustomEditorConfigurer (org.springframework.beans.factory.config)
AsyncExecutionInterceptor (org.springframework.aop.interceptor)
    AnnotationAsyncExecutionInterceptor (org.springframework.scheduling.annotation)
ExtendedBeanInfoFactory (org.springframework.beans)
SmartApplicationListener (org.springframework.context.event)
    GenericApplicationListener (org.springframework.context.event)
AspectJWeavingEnabler (org.springframework.context.weaving)
SimpleBeanInfoFactory (org.springframework.beans)
PriorityOrdered (org.springframework.core)
    ExposeInvocationInterceptor (org.springframework.aop.interceptor)
    ConfigurationClassPostProcessor (org.springframework.context.annotation)
    InitDestroyAnnotationBeanPostProcessor (org.springframework.beans.factory.annotation)
    RequiredAnnotationBeanPostProcessor (org.springframework.beans.factory.annotation)
    AutowiredAnnotationBeanPostProcessor (org.springframework.beans.factory.annotation)
    PropertyResourceConfigurer (org.springframework.beans.factory.config)
CustomScopeConfigurer (org.springframework.beans.factory.config)
AbstractPointcutAdvisor (org.springframework.aop.support)
    AsyncAnnotationAdvisor (org.springframework.scheduling.annotation)
    PersistenceExceptionTranslationAdvisor (org.springframework.dao.annotation)
    AbstractBeanFactoryPointcutAdvisor (org.springframework.aop.support)
    AbstractGenericPointcutAdvisor (org.springframework.aop.support)
    TransactionAttributeSourceAdvisor (org.springframework.transaction.interceptor)
CustomAutowireConfigurer (org.springframework.beans.factory.annotation)
TransactionSynchronization (org.springframework.transaction.support)
    TransactionalApplicationListenerSynchronization (org.springframework.transaction.event)
    ResourceHolderSynchronization (org.springframework.transaction.support)
    CleanupSynchronization in SimpleTransactionScope (org.springframework.transaction.support)
    TransactionSynchronizationAdapter (org.springframework.transaction.support)
    ConnectionSynchronization in DataSourceUtils (org.springframework.jdbc.datasource)
TransactionalEventListenerFactory (org.springframework.transaction.event)
AspectJPointcutAdvisor (org.springframework.aop.aspectj)
AspectJPrecedenceInformation (org.springframework.aop.aspectj)
    InstantiationModelAwarePointcutAdvisorImpl (org.springframework.aop.aspectj.annotation)
    AbstractAspectJAdvice (org.springframework.aop.aspectj)
DefaultEventListenerFactory (org.springframework.context.event)
ControllerAdviceBean (org.springframework.web.method)
DefaultIntroductionAdvisor (org.springframework.aop.support)

1.5.2 PriorityOrdered

org.springframework.core.PriorityOrdered接口仅是对Ordered接口的扩展,表示一个有序列,实现如下:

public interface PriorityOrdered extends Ordered {
}

1.5.2 ApplicationListener

org.springframework.context.ApplicationListener实现了Spring事件的监听功能:

@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
	void onApplicationEvent(E event);

	// Create a new {@code ApplicationListener} for the given payload consumer.
	static <T> ApplicationListener<PayloadApplicationEvent<T>> forPayload(Consumer<T> consumer) {
		return event -> consumer.accept(event.getPayload());
	}
}

ApplicationListener的实现类如下:

SmartApplicationListener (org.springframework.context.event)
    GenericApplicationListener (org.springframework.context.event)
TransactionalApplicationListener (org.springframework.transaction.event)
    TransactionalApplicationListenerMethodAdapter (org.springframework.transaction.event)
    TransactionalApplicationListenerAdapter (org.springframework.transaction.event)
ScheduledAnnotationBeanPostProcessor (org.springframework.scheduling.annotation)
event -> {...} in forPayload() in ApplicationListener
event -> {...} in forPayload() in TransactionalApplicationListener

1.5.3 ApplicationEventMulticaster

org.springframework.context.event.ApplicationEventMulticaster定义事件发送器的接口:

public interface ApplicationEventMulticaster {

	// Add a listener to be notified of all events.
	void addApplicationListener(ApplicationListener<?> listener);

	// Add a listener bean to be notified of all events.
	void addApplicationListenerBean(String listenerBeanName);

	// Remove a listener from the notification list.
	void removeApplicationListener(ApplicationListener<?> listener);

	// Remove a listener bean from the notification list.
	void removeApplicationListenerBean(String listenerBeanName);

	// Remove all matching listeners from the set of registered {@code ApplicationListener} instances.
	void removeApplicationListeners(Predicate<ApplicationListener<?>> predicate);

	// Remove all matching listener beans from the set of registered listener bean names.
	void removeApplicationListenerBeans(Predicate<String> predicate);

	// Remove all listeners registered with this multicaster.
	void removeAllListeners();

	// Multicast the given application event to appropriate listeners.
	void multicastEvent(ApplicationEvent event);

	// Multicast the given application event to appropriate listeners.
	void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType);
}

1.5.3.1 AbstractApplicationEventMulticaster

org.springframework.context.event.AbstractApplicationEventMulticaster定义事件发送的基础逻辑:

public abstract class AbstractApplicationEventMulticaster
		implements ApplicationEventMulticaster, BeanClassLoaderAware, BeanFactoryAware {
    // 定义的内部帮助类
	private final DefaultListenerRetriever defaultRetriever = new DefaultListenerRetriever();
    // ListenerCacheKey内部类,定义监听器的数据类型,CachedListenerRetriever为监听器的封装
	final Map<ListenerCacheKey, CachedListenerRetriever> retrieverCache = new ConcurrentHashMap<>(64);

	@Nullable
	private ClassLoader beanClassLoader;

	@Nullable
	private ConfigurableBeanFactory beanFactory;

	@Override
	public void addApplicationListener(ApplicationListener<?> listener) {
		synchronized (this.defaultRetriever) {
			// 可能是代理对象,获取对应的实际对象
			Object singletonTarget = AopProxyUtils.getSingletonTarget(listener);
			if (singletonTarget instanceof ApplicationListener) {
				this.defaultRetriever.applicationListeners.remove(singletonTarget);
			}
			this.defaultRetriever.applicationListeners.add(listener);
			this.retrieverCache.clear();
		}
	}

	protected Collection<ApplicationListener<?>> getApplicationListeners(
		...
	}

	private boolean supportsEvent(
			ConfigurableBeanFactory beanFactory, String listenerBeanName, ResolvableType eventType) {
        ...
	}

	protected boolean supportsEvent(Class<?> listenerType, ResolvableType eventType) {
		...
	}

	private static final class ListenerCacheKey implements Comparable<ListenerCacheKey> {

		private final ResolvableType eventType;

		@Nullable
		private final Class<?> sourceType;

	}
    
    // 封装特定类型的监听器
	private class CachedListenerRetriever {
		@Nullable
		public volatile Set<ApplicationListener<?>> applicationListeners;

		@Nullable
		public volatile Set<String> applicationListenerBeans;
	}

	private class DefaultListenerRetriever {

		public final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>();

		public final Set<String> applicationListenerBeans = new LinkedHashSet<>();

		public Collection<ApplicationListener<?>> getApplicationListeners() {
			List<ApplicationListener<?>> allListeners = new ArrayList<>(
					this.applicationListeners.size() + this.applicationListenerBeans.size());
			allListeners.addAll(this.applicationListeners);
			if (!this.applicationListenerBeans.isEmpty()) {
				BeanFactory beanFactory = getBeanFactory();
				for (String listenerBeanName : this.applicationListenerBeans) {
					try {
						ApplicationListener<?> listener =
								beanFactory.getBean(listenerBeanName, ApplicationListener.class);
						if (!allListeners.contains(listener)) {
							allListeners.add(listener);
						}
					}
					catch (NoSuchBeanDefinitionException ex) {
					}
				}
			}
            // 获取所有的ApplicationListener并进行排序,ApplicationListener的实现类都实现了Ordered接口
			AnnotationAwareOrderComparator.sort(allListeners);
			return allListeners;
		}
	}

}

1.5.3.2 SimpleApplicationEventMulticaster

org.springframework.context.event.SimpleApplicationEventMulticaster是AbstractApplicationEventMulticaster的实现类:

public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster {

	@Nullable // 执行线程
	private Executor taskExecutor;

	@Nullable // 错误处理器
	private ErrorHandler errorHandler;

	@Nullable
	private volatile Log lazyLogger;

	@Override
	public void multicastEvent(ApplicationEvent event) {
		multicastEvent(event, resolveDefaultEventType(event));
	}

	@Override
	public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
		ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
		Executor executor = getTaskExecutor();
		for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
			if (executor != null) {
                // 如果事件发送的线程池配置了,使用异步发送
				executor.execute(() -> invokeListener(listener, event));
			}
			else {
                // 独立线程没有配置,使用同步发送
				invokeListener(listener, event);
			}
		}
	}

	private ResolvableType resolveDefaultEventType(ApplicationEvent event) {
		return ResolvableType.forInstance(event);
	}

	protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
		ErrorHandler errorHandler = getErrorHandler();
		if (errorHandler != null) {
			try {
				doInvokeListener(listener, event);
			}
			catch (Throwable err) {
				errorHandler.handleError(err);
			}
		}
		else {
			doInvokeListener(listener, event);
		}
	}

	@SuppressWarnings({"rawtypes", "unchecked"})
	private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
		try {
            // 对每一个监听器,调用onApplicationEvent方法
			listener.onApplicationEvent(event);
		}
		catch (ClassCastException ex) {

		}
	}
}

1.5.2 ConversionService

org.springframework.core.convert.ConversionService定义了类型转换的逻辑:

public interface ConversionService {

	// Return {@code true} if objects of {@code sourceType} can be converted to the {@code targetType}.
	boolean canConvert(@Nullable Class<?> sourceType, Class<?> targetType);

	// Return {@code true} if objects of {@code sourceType} can be converted to the {@code targetType}.
	boolean canConvert(@Nullable TypeDescriptor sourceType, TypeDescriptor targetType);

	// Convert the given {@code source} to the specified {@code targetType}.
	@Nullable
	<T> T convert(@Nullable Object source, Class<T> targetType);

	// Convert the given {@code source} to the specified {@code targetType}.
	@Nullable
	Object convert(@Nullable Object source, @Nullable TypeDescriptor sourceType, TypeDescriptor targetType);
}

1.5.3 LoadTimeWeaver

org.springframework.instrument.classloading.LoadTimeWeaver用于动态类加载:

public interface LoadTimeWeaver {
	// Add a {@code ClassFileTransformer} to be applied by this {@code LoadTimeWeaver}.
	void addTransformer(ClassFileTransformer transformer);

	// Return a {@code ClassLoader} that supports instrumentation through AspectJ-style load-time weaving based on user-defined {@link ClassFileTransformer ClassFileTransformers}.
	ClassLoader getInstrumentableClassLoader();

	// Return a throwaway {@code ClassLoader}, enabling classes to be loaded and inspected without affecting the parent {@code ClassLoader}.
	ClassLoader getThrowawayClassLoader();
}

1.5.4 Lifecycle

org.springframework.context.Lifecycle定义了方法的启动暂停生命周期控制:

public interface Lifecycle {

	// Start this component.
	void start();

	// Stop this component, typically in a synchronous fashion
	void stop();

	// Check whether this component is currently running.
	boolean isRunning();
}

1.5.5 BeanDefinition

org.springframework.beans.factory.config.BeanDefinition定义描述类信息的接口:

public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement {

	// Scope identifier for the standard singleton scope
	String SCOPE_SINGLETON = ConfigurableBeanFactory.SCOPE_SINGLETON;

	// Scope identifier for the standard prototype scope
	String SCOPE_PROTOTYPE = ConfigurableBeanFactory.SCOPE_PROTOTYPE;


	// Role hint indicating that a {@code BeanDefinition} is a major part of the application. Typically corresponds to a user-defined bean.
	int ROLE_APPLICATION = 0;

	// Role hint indicating that a {@code BeanDefinition} is a supporting part of some larger configuration, typically an outer
	int ROLE_SUPPORT = 1;

	// Role hint indicating that a {@code BeanDefinition} is providing an entirely background role and has no relevance to the end-user.
	int ROLE_INFRASTRUCTURE = 2;

	void setParentName(@Nullable String parentName);

	@Nullable
	String getParentName();

	// Specify the bean class name of this bean definition.
	void setBeanClassName(@Nullable String beanClassName);

	// Return the current bean class name of this bean definition.
	@Nullable
	String getBeanClassName();

	void setScope(@Nullable String scope);

	@Nullable
	String getScope();

	void setLazyInit(boolean lazyInit);

	boolean isLazyInit();

	void setDependsOn(@Nullable String... dependsOn);

	// Return the bean names that this bean depends on.
	@Nullable
	String[] getDependsOn();

	void setAutowireCandidate(boolean autowireCandidate);

	boolean isAutowireCandidate();

	// Set whether this bean is a primary autowire candidate.
	void setPrimary(boolean primary);

	boolean isPrimary();

	void setFactoryBeanName(@Nullable String factoryBeanName);

	@Nullable
	String getFactoryBeanName();

	void setFactoryMethodName(@Nullable String factoryMethodName);

	@Nullable
	String getFactoryMethodName();

	ConstructorArgumentValues getConstructorArgumentValues();

	default boolean hasConstructorArgumentValues() {
		return !getConstructorArgumentValues().isEmpty();
	}

	MutablePropertyValues getPropertyValues();

	default boolean hasPropertyValues() {
		return !getPropertyValues().isEmpty();
	}

	void setInitMethodName(@Nullable String initMethodName);

	@Nullable
	String getInitMethodName();

	void setDestroyMethodName(@Nullable String destroyMethodName);

	@Nullable
	String getDestroyMethodName();

	void setRole(int role);

	int getRole();

	void setDescription(@Nullable String description);

	// Return a human-readable description of this bean definition.
	@Nullable
	String getDescription();

	ResolvableType getResolvableType();

	boolean isSingleton();

	boolean isPrototype();

	boolean isAbstract();

	@Nullable
	String getResourceDescription();

	@Nullable
	BeanDefinition getOriginatingBeanDefinition();
}

BeanDefinition的继承类如下:

AnnotatedBeanDefinition (org.springframework.beans.factory.annotation)
    ScannedGenericBeanDefinition (org.springframework.context.annotation)
    ConfigurationClassBeanDefinition in ConfigurationClassBeanDefinitionReader (org.springframework.context.annotation)
    AnnotatedGenericBeanDefinition (org.springframework.beans.factory.annotation)
AbstractBeanDefinition (org.springframework.beans.factory.support)
    RootBeanDefinition (org.springframework.beans.factory.support)
        ConfigurationClassBeanDefinition in ConfigurationClassBeanDefinitionReader (org.springframework.context.annotation)
        ClassDerivedBeanDefinition in GenericApplicationContext (org.springframework.context.support)
    ChildBeanDefinition (org.springframework.beans.factory.support)
    GenericBeanDefinition (org.springframework.beans.factory.support)
        ScannedGenericBeanDefinition (org.springframework.context.annotation)
        AnnotatedGenericBeanDefinition (org.springframework.beans.factory.annotation)

1.5.5.1 AttributeAccessor

org.springframework.core.AttributeAccessor接口定义了一个通用协定,用于向/从任意对象附加和访问元数据。

public interface AttributeAccessor {
	void setAttribute(String name, @Nullable Object value);

	@Nullable
	Object getAttribute(String name);

	@SuppressWarnings("unchecked")
	default <T> T computeAttribute(String name, Function<String, T> computeFunction) {
		Assert.notNull(name, "Name must not be null");
		Assert.notNull(computeFunction, "Compute function must not be null");
		Object value = getAttribute(name);
		if (value == null) {
			value = computeFunction.apply(name);
			Assert.state(value != null,
					() -> String.format("Compute function must not return null for attribute named '%s'", name));
			setAttribute(name, value);
		}
		return (T) value;
	}

	@Nullable
	Object removeAttribute(String name);

	boolean hasAttribute(String name);

	String[] attributeNames();
}

1.5.5.2 BeanMetadataElement

org.springframework.beans.BeanMetadataElement由携带配置源对象的bean元数据元素实现的接口:

public interface BeanMetadataElement {
	// Return the configuration source {@code Object} for this metadata element
	@Nullable
	default Object getSource() {
		return null;
	}
}

1.5.5.3 AttributeAccessorSupport

org.springframework.core.AttributeAccessorSupport是AttributeAccessors的基础实现类:

public abstract class AttributeAccessorSupport implements AttributeAccessor, Serializable {

	/** Map with String keys and Object values. */
	private final Map<String, Object> attributes = new LinkedHashMap<>();

	@Override
	@SuppressWarnings("unchecked")
	public <T> T computeAttribute(String name, Function<String, T> computeFunction) {
		Assert.notNull(name, "Name must not be null");
		Assert.notNull(computeFunction, "Compute function must not be null");
		Object value = this.attributes.computeIfAbsent(name, computeFunction);
		Assert.state(value != null,
				() -> String.format("Compute function must not return null for attribute named '%s'", name));
		return (T) value;
	}

	@Override
	@Nullable
	public Object removeAttribute(String name) {
		Assert.notNull(name, "Name must not be null");
		return this.attributes.remove(name);
	}

	@Override
	public boolean hasAttribute(String name) {
		Assert.notNull(name, "Name must not be null");
		return this.attributes.containsKey(name);
	}

	@Override
	public String[] attributeNames() {
		return StringUtils.toStringArray(this.attributes.keySet());
	}
}

1.5.5.4 BeanMetadataAttributeAccessor

org.springframework.beans.BeanMetadataAttributeAccessor扩展AttributeAccessorSupport,同时具备配置源属性:

public class BeanMetadataAttributeAccessor extends AttributeAccessorSupport implements BeanMetadataElement {
	@Nullable
	private Object source;

	public void addMetadataAttribute(BeanMetadataAttribute attribute) {
		super.setAttribute(attribute.getName(), attribute);
	}

	@Nullable
	public BeanMetadataAttribute getMetadataAttribute(String name) {
		return (BeanMetadataAttribute) super.getAttribute(name);
	}

	@Override
	public void setAttribute(String name, @Nullable Object value) {
		super.setAttribute(name, new BeanMetadataAttribute(name, value));
	}

	@Override
	@Nullable
	public Object getAttribute(String name) {
		BeanMetadataAttribute attribute = (BeanMetadataAttribute) super.getAttribute(name);
		return (attribute != null ? attribute.getValue() : null);
	}

	@Override
	@Nullable
	public Object removeAttribute(String name) {
		BeanMetadataAttribute attribute = (BeanMetadataAttribute) super.removeAttribute(name);
		return (attribute != null ? attribute.getValue() : null);
	}
}

1.5.5.5 BeanMetadataAttribute

org.springframework.beans.BeanMetadataAttribute为Bean元信息封装类:

public class BeanMetadataAttribute implements BeanMetadataElement {

	private final String name;

	@Nullable
	private final Object value;

	@Nullable
	private Object source;
}

1.5.5.6 AbstractBeanDefinition

org.springframework.beans.factory.support.AbstractBeanDefinition封装基本Bean信息:


public abstract class AbstractBeanDefinition extends BeanMetadataAttributeAccessor
		implements BeanDefinition, Cloneable {
	// Constant for the default scope name, equivalent to singleton
	public static final String SCOPE_DEFAULT = "";

	// Constant that indicates no external autowiring at all.
	public static final int AUTOWIRE_NO = AutowireCapableBeanFactory.AUTOWIRE_NO;

	public static final int AUTOWIRE_BY_NAME = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;

	public static final int AUTOWIRE_BY_TYPE = AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE;

	public static final int AUTOWIRE_CONSTRUCTOR = AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR;

	@Deprecated
	public static final int AUTOWIRE_AUTODETECT = AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT;

	// Constant that indicates no dependency check at all.
	public static final int DEPENDENCY_CHECK_NONE = 0;

	// Constant that indicates dependency checking for object references.
	public static final int DEPENDENCY_CHECK_OBJECTS = 1;

	// Constant that indicates dependency checking for "simple" properties.
	public static final int DEPENDENCY_CHECK_SIMPLE = 2;

	public static final int DEPENDENCY_CHECK_ALL = 3;

	public static final String INFER_METHOD = "(inferred)";

	@Nullable
	private volatile Object beanClass;

	@Nullable
	private String scope = SCOPE_DEFAULT;

	private boolean abstractFlag = false;

	@Nullable
	private Boolean lazyInit;

	private int autowireMode = AUTOWIRE_NO;

	private int dependencyCheck = DEPENDENCY_CHECK_NONE;

	@Nullable
	private String[] dependsOn;

	private boolean autowireCandidate = true;

	private boolean primary = false;

	private final Map<String, AutowireCandidateQualifier> qualifiers = new LinkedHashMap<>();

	@Nullable
	private Supplier<?> instanceSupplier;

	private boolean nonPublicAccessAllowed = true;

	private boolean lenientConstructorResolution = true;

	@Nullable
	private String factoryBeanName;

	@Nullable
	private String factoryMethodName;

	@Nullable // 对于构造方法参数的封装
	private ConstructorArgumentValues constructorArgumentValues;

	@Nullable
	private MutablePropertyValues propertyValues;
    
    // 重载方法的信息封装类
	private MethodOverrides methodOverrides = new MethodOverrides();

	@Nullable
	private String initMethodName;

	@Nullable
	private String destroyMethodName;

	private boolean enforceInitMethod = true;

	private boolean enforceDestroyMethod = true;

	private boolean synthetic = false;

	private int role = BeanDefinition.ROLE_APPLICATION;

	@Nullable
	private String description;

	@Nullable
	private Resource resource;

	public int getResolvedAutowireMode() {
		if (this.autowireMode == AUTOWIRE_AUTODETECT) {
			// Work out whether to apply setter autowiring or constructor autowiring.
			// If it has a no-arg constructor it's deemed to be setter autowiring,
			// otherwise we'll try constructor autowiring.
			Constructor<?>[] constructors = getBeanClass().getConstructors();
			for (Constructor<?> constructor : constructors) {
				if (constructor.getParameterCount() == 0) {
					return AUTOWIRE_BY_TYPE;
				}
			}
			return AUTOWIRE_CONSTRUCTOR;
		}
		else {
			return this.autowireMode;
		}
	}

	public void addQualifier(AutowireCandidateQualifier qualifier) {
		this.qualifiers.put(qualifier.getTypeName(), qualifier);
	}
    
    // 校验方法重载信息
	protected void prepareMethodOverride(MethodOverride mo) throws BeanDefinitionValidationException {
		int count = ClassUtils.getMethodCountForName(getBeanClass(), mo.getMethodName());
		if (count == 0) {
			throw new BeanDefinitionValidationException(
					"Invalid method override: no method with name '" + mo.getMethodName() +
					"' on class [" + getBeanClassName() + "]");
		}
		else if (count == 1) {
			// Mark override as not overloaded, to avoid the overhead of arg type checking.
			mo.setOverloaded(false);
		}
	}
}

1.5.5.7 ChildBeanDefinition

org.springframework.beans.factory.support.ChildBeanDefinition子类Bean定义信息:

public class ChildBeanDefinition extends AbstractBeanDefinition {
	@Nullable
	private String parentName;
}

1.5.5.8 GenericBeanDefinition

org.springframework.beans.factory.support.GenericBeanDefinition是用于标准Bean定义目的的一站式服务:

public class GenericBeanDefinition extends AbstractBeanDefinition {
	@Nullable
	private String parentName;
}

1.5.5.9 BeanDefinitionHolder

org.springframework.beans.factory.config.BeanDefinitionHolder为对BeanDefinition的封装:

public class BeanDefinitionHolder implements BeanMetadataElement {
	private final BeanDefinition beanDefinition;

	private final String beanName;

	@Nullable
	private final String[] aliases;
}

1.5.5.10 RootBeanDefinition

org.springframework.beans.factory.support.RootBeanDefinition根Bean定义表示在运行时支持Spring BeanFactory中特定Bean的合并Bean定义:

public class RootBeanDefinition extends AbstractBeanDefinition {
	@Nullable
	private BeanDefinitionHolder decoratedDefinition;

	@Nullable
	private AnnotatedElement qualifiedElement;

	/** Determines if the definition needs to be re-merged. */
	volatile boolean stale;

	boolean allowCaching = true;

	boolean isFactoryMethodUnique;

	@Nullable
	volatile ResolvableType targetType;

	/** Package-visible field for caching the determined Class of a given bean definition. */
	@Nullable
	volatile Class<?> resolvedTargetType;

	/** Package-visible field for caching if the bean is a factory bean. */
	@Nullable
	volatile Boolean isFactoryBean;

	/** Package-visible field for caching the return type of a generically typed factory method. */
	@Nullable
	volatile ResolvableType factoryMethodReturnType;

	/** Package-visible field for caching a unique factory method candidate for introspection. */
	@Nullable
	volatile Method factoryMethodToIntrospect;

	/** Package-visible field for caching a resolved destroy method name (also for inferred). */
	@Nullable
	volatile String resolvedDestroyMethodName;

	/** Common lock for the four constructor fields below. */
	final Object constructorArgumentLock = new Object();

	/** Package-visible field for caching the resolved constructor or factory method. */
	@Nullable
	Executable resolvedConstructorOrFactoryMethod;

	/** Package-visible field that marks the constructor arguments as resolved. */
	boolean constructorArgumentsResolved = false;

	/** Package-visible field for caching fully resolved constructor arguments. */
	@Nullable
	Object[] resolvedConstructorArguments;

	/** Package-visible field for caching partly prepared constructor arguments. */
	@Nullable
	Object[] preparedConstructorArguments;

	/** Common lock for the two post-processing fields below. */
	final Object postProcessingLock = new Object();

	/** Package-visible field that indicates MergedBeanDefinitionPostProcessor having been applied. */
	boolean postProcessed = false;

	/** Package-visible field that indicates a before-instantiation post-processor having kicked in. */
	@Nullable
	volatile Boolean beforeInstantiationResolved;

	@Nullable
	private Set<Member> externallyManagedConfigMembers;

	@Nullable
	private Set<String> externallyManagedInitMethods;

	@Nullable
	private Set<String> externallyManagedDestroyMethods;

	public RootBeanDefinition(@Nullable Class<?> beanClass, int autowireMode, boolean dependencyCheck) {
		super();
		setBeanClass(beanClass);
		setAutowireMode(autowireMode);
		if (dependencyCheck && getResolvedAutowireMode() != AUTOWIRE_CONSTRUCTOR) {
			setDependencyCheck(DEPENDENCY_CHECK_OBJECTS);
		}
	}

	public void registerExternallyManagedConfigMember(Member configMember) {
		synchronized (this.postProcessingLock) {
			if (this.externallyManagedConfigMembers == null) {
				this.externallyManagedConfigMembers = new LinkedHashSet<>(1);
			}
			this.externallyManagedConfigMembers.add(configMember);
		}
	}
}

1.5.6 InstantiationStrategy

org.springframework.beans.factory.support.InstantiationStrategy对应于RootBeanDefinition的Bean实例化构建策略接口:

public interface InstantiationStrategy {

	// 使用指定的BeanFactory新建Bean对象
	Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner)
			throws BeansException;

	// 使用对应的构造方法新建Bean对象
	Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
			Constructor<?> ctor, Object... args) throws BeansException;

	// 使用factoryBean中的factoryMethod方法新建对象
	Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
			@Nullable Object factoryBean, Method factoryMethod, Object... args)
			throws BeansException;

}

1.5.6.1 SimpleInstantiationStrategy

InstantiationStrategy的简单实现,org.springframework.beans.factory.support.SimpleInstantiationStrategy:

public class SimpleInstantiationStrategy implements InstantiationStrategy {

	private static final ThreadLocal<Method> currentlyInvokedFactoryMethod = new ThreadLocal<>();

	@Nullable
	public static Method getCurrentlyInvokedFactoryMethod() {
		return currentlyInvokedFactoryMethod.get();
	}

	@Override
	public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
		// Don't override the class with CGLIB if no overrides.
		if (!bd.hasMethodOverrides()) {
			Constructor<?> constructorToUse;
			synchronized (bd.constructorArgumentLock) {
                // 获取BeanDefinition中的构造方法
				constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
				if (constructorToUse == null) {
					final Class<?> clazz = bd.getBeanClass();
					if (clazz.isInterface()) {
						throw new BeanInstantiationException(clazz, "Specified class is an interface");
					}
					try {
						if (System.getSecurityManager() != null) {
							constructorToUse = AccessController.doPrivileged(
									(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
						}
						else {
							constructorToUse = clazz.getDeclaredConstructor();
						}
						bd.resolvedConstructorOrFactoryMethod = constructorToUse;
					}
					catch (Throwable ex) {
						throw new BeanInstantiationException(clazz, "No default constructor found", ex);
					}
				}
			}
            // 使用BeanUtils工具类实例化对象
			return BeanUtils.instantiateClass(constructorToUse);
		}
		else {
			// Must generate CGLIB subclass.
			return instantiateWithMethodInjection(bd, beanName, owner);
		}
	}

	protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
		throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
	}

	@Override
	public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
			final Constructor<?> ctor, Object... args) {
		if (!bd.hasMethodOverrides()) {
			if (System.getSecurityManager() != null) {
				// use own privileged to change accessibility (when security is on)
				AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
					ReflectionUtils.makeAccessible(ctor);
					return null;
				});
			}
			return BeanUtils.instantiateClass(ctor, args);
		}
		else {
			return instantiateWithMethodInjection(bd, beanName, owner, ctor, args);
		}
	}

	/**
	 * Subclasses can override this method, which is implemented to throw
	 * UnsupportedOperationException, if they can instantiate an object with
	 * the Method Injection specified in the given RootBeanDefinition.
	 * Instantiation should use the given constructor and parameters.
	 */
	protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName,
			BeanFactory owner, @Nullable Constructor<?> ctor, Object... args) {

		throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
	}

	@Override
	public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
			@Nullable Object factoryBean, final Method factoryMethod, Object... args) {

		try {
			if (System.getSecurityManager() != null) {
				AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
					ReflectionUtils.makeAccessible(factoryMethod);
					return null;
				});
			}
			else {
				ReflectionUtils.makeAccessible(factoryMethod);
			}

			Method priorInvokedFactoryMethod = currentlyInvokedFactoryMethod.get();
			try {
				currentlyInvokedFactoryMethod.set(factoryMethod);
				Object result = factoryMethod.invoke(factoryBean, args);
				if (result == null) {
					result = new NullBean();
				}
				return result;
			}
			finally {
				if (priorInvokedFactoryMethod != null) {
					currentlyInvokedFactoryMethod.set(priorInvokedFactoryMethod);
				}
				else {
					currentlyInvokedFactoryMethod.remove();
				}
			}
		}
		catch (IllegalArgumentException ex) {
			throw new BeanInstantiationException(factoryMethod,
					"Illegal arguments to factory method '" + factoryMethod.getName() + "'; " +
					"args: " + StringUtils.arrayToCommaDelimitedString(args), ex);
		}
		catch (IllegalAccessException ex) {
			throw new BeanInstantiationException(factoryMethod,
					"Cannot access factory method '" + factoryMethod.getName() + "'; is it public?", ex);
		}
		catch (InvocationTargetException ex) {
			String msg = "Factory method '" + factoryMethod.getName() + "' threw exception";
			if (bd.getFactoryBeanName() != null && owner instanceof ConfigurableBeanFactory &&
					((ConfigurableBeanFactory) owner).isCurrentlyInCreation(bd.getFactoryBeanName())) {
				msg = "Circular reference involving containing bean '" + bd.getFactoryBeanName() + "' - consider " +
						"declaring the factory method as static for independence from its containing instance. " + msg;
			}
			throw new BeanInstantiationException(factoryMethod, msg, ex.getTargetException());
		}
	}

}