Spring 源码学习(八)—— 对象工厂

IOC 作为 Spring 的核心,其是通过对象工厂对其进行实现,核心对象工厂类为 DefaultListableBeanFactory,其继承与实现关系如上图所示,因此本文将从接口出发对该对象工厂类进行分析。

一 接口

1 AliasRegistry 接口

AliasRegistry 接口用于提供对对象别名映射操作相关功能;

1.1 registerAlias 方法

registerAlias 方法用于注册对象名与别名映射;

java 复制代码
public interface AliasRegistry {
	void registerAlias(String name, String alias);
}

1.2 removeAlias 方法

removeAlias 方法移除指定映射名;

java 复制代码
public interface AliasRegistry {
	void removeAlias(String alias);
}

1.3 isAlias 方法

isAlias 方法用于判断指定名字是否为别名;

java 复制代码
public interface AliasRegistry {
	boolean isAlias(String name);
}

1.4 getAliases 方法

getAliases 方法获取指定对象名关联的别名数组;

java 复制代码
public interface AliasRegistry {
	String[] getAliases(String name);
}

2 SingletonBeanRegistry 接口

SingletonBeanRegistry 接口提供了单例对象处理功能;

2.1 registerSingleton 方法

registerSingleton 方法用于将 singletonObject 对象以 beanName 名注册为单例对象;

java 复制代码
public interface SingletonBeanRegistry {
	void registerSingleton(String beanName, Object singletonObject);
}

2.2 getSingleton 方法

getSingleton 方法用于指定名字的单例对象;

java 复制代码
public interface SingletonBeanRegistry {
	@Nullable
	Object getSingleton(String beanName);
}

2.3 containsSingleton 方法

containsSingleton 方法用于判断是否已经注册了指定名字的单例对象;

java 复制代码
public interface SingletonBeanRegistry {
	boolean containsSingleton(String beanName);
}

2.4 getSingletonNames 方法

getSingletonNames 方法用于获取当前已注册的所有单例对象名数组;

java 复制代码
public interface SingletonBeanRegistry {
	String[] getSingletonNames();
}

2.5 getSingletonCount 方法

getSingletonCount 方法获取当前已注册的单例对象个数;

java 复制代码
public interface SingletonBeanRegistry {
	int getSingletonCount();
}

1.6 getSingletonMutex 方法

getSingletonMutex 方法用于获取当前注册器所使用的单例互斥体;

java 复制代码
public interface SingletonBeanRegistry {
	Object getSingletonMutex();
}

3 ConfigurableBeanFactory 接口

ConfigurableBeanFactory 接口向外提供了对象工厂的配置的获取及设置功能;

3.1 常量

ConfigurableBeanFactory 接口的常量保存了用于存储作用域名的常量,SCOPE_SINGLETON 常量保存的是单例对象作用域名,而 SCOPE_PROTOTYPE 常量则保存原型模式对象作用域名;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {

	String SCOPE_SINGLETON = "singleton";

	String SCOPE_PROTOTYPE = "prototype";
}

3.2 setParentBeanFactory 方法

setParentBeanFactory 方法用于为对象工厂设置父工厂对象;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	void setParentBeanFactory(BeanFactory parentBeanFactory) throws IllegalStateException;
}

3.3 ClassLoader 方法

对于对象类加载器,ConfigurableBeanFactory 接口提供了设置对象工厂的类加载器的 setBeanClassLoader 以及获取当前工厂使用的类加载器的 getBeanClassLoader 方法;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	@Nullable
	ClassLoader getBeanClassLoader();

	void setBeanClassLoader(@Nullable ClassLoader beanClassLoader);
}

而对于在对象工厂完成引导后删除的临时类加载器,其提供了用于设置临时类加载器的 setTempClassLoader 方法及获取临时类加载器的 getTempClassLoader 方法;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	void setTempClassLoader(@Nullable ClassLoader tempClassLoader);

	@Nullable
	ClassLoader getTempClassLoader();
}

3.4 cacheBeanMetadata 方法

对于对象工厂是否缓存元数据对象,ConfigurableBeanFactory 接口提供了 setCacheBeanMetadata 与 isCacheBeanMetadata 方法分别用于设置是否开启元数据缓存及获取当前是否开启了元数据缓存,该开关默认开启,关闭时表示可以热刷新对象注册表;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	void setCacheBeanMetadata(boolean cacheBeanMetadata);

	boolean isCacheBeanMetadata();
}

3.5 BeanExpressionResolver 方法

BeanExpressionResolver 对象用于对象注册表值的解析,其提供了用于获取对象解析器的 getBeanExpressionResolver 方法与设置对象解析器的 setBeanExpressionResolver 方法;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	void setBeanExpressionResolver(@Nullable BeanExpressionResolver resolver);

	@Nullable
	BeanExpressionResolver getBeanExpressionResolver();
}

3.6 属性解析对象相关方法

ConversionService 对象则是用于补充 PropertyEditors 对象提供对象属性的解析功能,其也提供了用于获取和设置的 get 和 set 方法;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	void setBeanExpressionResolver(@Nullable BeanExpressionResolver resolver);

	@Nullable
	BeanExpressionResolver getBeanExpressionResolver();
}

addPropertyEditorRegistrar 方法用于向对象工厂中添加 PropertyEditorRegistrar 属性编辑器注册对象;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar);
}

registerCustomEditor 方法用于向对象工厂的通用注册器中注册指定类型的 PropertyEditors 属性解析类型;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass);
}

copyRegisteredEditorsTo 方法用于将当前对象工厂中注册的公共编辑器对象复制到指定属性编辑器注册器参数中;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	void copyRegisteredEditorsTo(PropertyEditorRegistry registry);
}

3.7 TypeConverter 方法

TypeConverter 对象用于对象属性或构造方法参数的类型转换,其也提供了用于获取和设置的 get 和 set 方法;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	void setTypeConverter(TypeConverter typeConverter);

	TypeConverter getTypeConverter();
}

3.8 EmbeddedValue 方法

addEmbeddedValueResolver 与 hasEmbeddedValueResolver 方法分别用于向对象工厂中添加嵌入式值字符串解析器及判断当前是否存在嵌入式值解析器;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	void addEmbeddedValueResolver(StringValueResolver valueResolver);

	boolean hasEmbeddedValueResolver();
}

resolveEmbeddedValue 方法则是用于解析对象的 value 值;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	@Nullable
	String resolveEmbeddedValue(String value);
}

3.9 BeanPostProcessor 方法

addBeanPostProcessor 与 getBeanPostProcessorCount 方法分别用于向对象工厂中添加 BeanPostProcessor 对象前处理器对象及当前对象工厂中的 BeanPostProcessor 对象前处理器的数量;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	void addBeanPostProcessor(BeanPostProcessor beanPostProcessor);

	int getBeanPostProcessorCount();
}

3.10 registerScope 方法

registerScope 方法用于向对象工厂中注册对象作用域名与作用域对象的映射;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	void registerScope(String scopeName, Scope scope);
}

getRegisteredScopeNames 方法用于获取当前注册的所有作用域名数组;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	String[] getRegisteredScopeNames();
}

getRegisteredScope 则用于获取指定名字对应的作用域对象

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	@Nullable
	Scope getRegisteredScope(String scopeName);
}

3.11 getAccessControlContext 方法

getAccessControlContext 方法用于获取当前对象工厂的访问控制上下文;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	AccessControlContext getAccessControlContext();
}

3.12 copyConfigurationFrom 方法

copyConfigurationFrom 方法用于将指定 ConfigurableBeanFactory 对象参数中的所有配置复制到当前对象中;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
    void copyConfigurationFrom(ConfigurableBeanFactory otherFactory);
}

3.13 Alias 方法

registerAlias 方法向对象工厂中注册别名,而 resolveAliases 方法则会使用 valueResolver 参数解析所有别名对象;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	void registerAlias(String beanName, String alias) throws BeanDefinitionStoreException;

	void resolveAliases(StringValueResolver valueResolver);
}

3.14 getMergedBeanDefinition 方法

getMergedBeanDefinition 方法用于获取指定对象名对象的合并对象注册表;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	BeanDefinition getMergedBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
}

3.15 isFactoryBean 方法

isFactoryBean 方法用于判断指定对象是否为工厂对象;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException;
}

3.16 CurrentlyInCreation 方法

setCurrentlyInCreation 方法显示设置指定对象的 inCreation 属性;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	void setCurrentlyInCreation(String beanName, boolean inCreation);
}

isCurrentlyInCreation 方法判断指定对象是否处于 inCreation 状态;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	boolean isCurrentlyInCreation(String beanName);
}

3.17 DependentBean 方法

registerDependentBean、getDependentBeans 及 getDependentBeans 分别用于为指定对象设置依赖对象、获取依赖指定对象的对象名数组及获取指定对象的依赖对象名数组;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	void registerDependentBean(String beanName, String dependentBeanName);

	String[] getDependentBeans(String beanName);

	String[] getDependenciesForBean(String beanName);
}

3.18 destroy 方法

destroyBean、destroyScopedBean 及 destroySingletons 分别用于销毁指定对象、销毁指定作用域对象及销毁所有单例对象;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	void destroyBean(String beanName, Object beanInstance);

	void destroyScopedBean(String beanName);

	void destroySingletons();
}

4 AutowireCapableBeanFactory 接口

AutowireCapableBeanFactory 接口扩展了 BeanFactory 接口的对象的自动装配功能;

4.1 常量

AutowireCapableBeanFactory 接口的常量分为两类,第一类标识了自动注入的模式,其中 AUTOWIRE_NO 常量标识不需要自动注入,AUTOWIRE_BY_NAME 常量标识根据名称进行注入,AUTOWIRE_BY_TYPE 常量则标识根据类型自动注入,AUTOWIRE_CONSTRUCTOR 常量标识的是使用构造器进行自动注入;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {

	int AUTOWIRE_NO = 0;

	int AUTOWIRE_BY_NAME = 1;

	int AUTOWIRE_BY_TYPE = 2;

	int AUTOWIRE_CONSTRUCTOR = 3;
}

除了标识自动注入常量之外,AutowireCapableBeanFactory 接口还拥有一个保存初始化原始实例时,原始实例使用的后缀;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	String ORIGINAL_INSTANCE_SUFFIX = ".ORIGINAL";
}

4.2 createBean 方法

createBean 方法用于完全创建指定类型对象,保存执行所有需执行的 BeanPostProcessor 处理器;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	<T> T createBean(Class<T> beanClass) throws BeansException;
}

三参数的 createBean 方法使用指定自动注入模式与是否需要对依赖进行验证来完整创建对象;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
    Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;
}

4.3 autowire 方法

autowireBean 相关方法为对象实例化后的执行后处理器进行属性的自动注入,他也可以指定对象注入模式与是否需要依赖检查,同时也为对象属性提供了 autowireBeanProperties 注入方法;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	void autowireBean(Object existingBean) throws BeansException;

	Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;

	void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck)
			throws BeansException;
}

4.4 configureBean 方法

configureBean 方法用于配置指定对象,包括属性的自动注入与应用,对象工厂相关回调及执行需执行的后处理器;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	Object configureBean(Object existingBean, String beanName) throws BeansException;
}

4.5 applyBeanPropertyValues 方法

applyBeanPropertyValues 方法将指定对象实例应用到指定名字的对象注册表中;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException;
}

4.6 initializeBean 方法

initializeBean 方法使用指定对象工厂回调来初始化指定实例;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	Object initializeBean(Object existingBean, String beanName) throws BeansException;
}

4.7 applyBeanPostProcessors 方法

applyBeanPostProcessorsBeforeInitialization 与 applyBeanPostProcessorsAfterInitialization 方法分别对指定实例执行 postProcessBeforeInitialization 与 postProcessAfterInitialization 后处理方法;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
			throws BeansException;

	Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
			throws BeansException;
}

4.8 destroyBean 方法

destroyBean 方法直接用于销毁指定实例;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	void destroyBean(Object existingBean);
}

4.9 resolve 方法

resolveNamedBean 方法用于获取与给定对象类型唯一匹配的 bean 对象;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	<T> NamedBeanHolder<T> resolveNamedBean(Class<T> requiredType) throws BeansException;
}

resolveDependency 方法根据对象名与依赖限定符对象来获取指定依赖对象;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	Object resolveBeanByName(String name, DependencyDescriptor descriptor) throws BeansException;
}

resolveDependency 方法则用于获取指定对象中满足指定依赖限定符的对象,除了 descriptor 依赖限定符与 requestingBeanName 需要对象名之外,还可以使用 autowiredBeanNames 来限制自动注入名及 typeConverter 对象转换器对象;

java 复制代码
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
	@Nullable
	Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName) throws BeansException;

	@Nullable
	Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException;
}

5 ConfigurableListableBeanFactory 接口

ConfigurableListableBeanFactory 接口也是用于提供配置对象工厂的功能,其扩展了 ConfigurableBeanFactory 接口的配置方法,增加了对 bean 对象定义的分析修改及单例与实例化的功能;

5.1 ignoreDependency 方法

ignoreDependencyType 与 ignoreDependencyInterface 方法直接用于忽略指定类型对象的自动加载;

java 复制代码
public interface SingletonBeanRegistry {
	void ignoreDependencyType(Class<?> type);

	void ignoreDependencyInterface(Class<?> ifc);
}

5.2 registerResolvableDependency 方法

registerResolvableDependency 方法直接将指定 autowiredValue 参数值与 dependencyType 依赖类型的关联注册到对象工厂之中;

java 复制代码
public interface SingletonBeanRegistry {
	void registerResolvableDependency(Class<?> dependencyType, @Nullable Object autowiredValue);
}

5.3 isAutowireCandidate 方法

isAutowireCandidate 方法判断指定对象是否满足 descriptor 依赖限制;

java 复制代码
public interface SingletonBeanRegistry {
	boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor)
			throws NoSuchBeanDefinitionException;
}

5.4 getBeanDefinition 方法

getBeanDefinition 方法用于获取指定对象注册表;

java 复制代码
public interface SingletonBeanRegistry {
	BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
}

5.5 getBeanNamesIterator 方法

getBeanNamesIterator 方法获取当前对象工厂中对象名迭代器;

java 复制代码
public interface SingletonBeanRegistry {
	Iterator<String> getBeanNamesIterator();
}

5.6 clearMetadataCache 方法

clearMetadataCache 方法用于清除元数据缓存;

java 复制代码
public interface SingletonBeanRegistry {
	void clearMetadataCache();
}

5.7 freezeConfiguration 方法

freezeConfiguration 与 freezeConfiguration 方法分别用于冻结配置及判断当前配置是否已经被冻结;

java 复制代码
public interface SingletonBeanRegistry {
	void freezeConfiguration();

	boolean isConfigurationFrozen();
}

5.8 preInstantiateSingletons 方法

preInstantiateSingletons 方法对工厂中所有单例对象全进行预实例化;

java 复制代码
public interface SingletonBeanRegistry {
	void preInstantiateSingletons() throws BeansException;
}

二 SimpleAliasRegistry 类

SimpleAliasRegistry 类为 AliasRegistry 接口提供了一个简单的实现;其内部使用了一个 Map 集合对象来存储别名与对象名映射;

java 复制代码
public class SimpleAliasRegistry implements AliasRegistry {
	private final Map<String, String> aliasMap = new ConcurrentHashMap<>(16);
}

1 重写方法

1.1 registerAlias 方法

registerAlias 方法首先对 name 和 value 属性进行非空验证,通过验证后对 aliasMap 属性加锁,随后若 alias 与 name 参数想等时从 aliasMap 属性中移除 alias 参数别名,否则判断 alias 参数是否已经设置为别名了,若设置了且对象名与 name 参数想等时直接返回,否则在不允许对别名进行重写时直接抛出异常;随后调用 checkForAliasCircle 方法验证是否为循环依赖,验证通过后将 alias 与 name 参数映射保存到 aliasMap 属性中;

java 复制代码
public class SimpleAliasRegistry implements AliasRegistry {
	@Override
	public void registerAlias(String name, String alias) {
		Assert.hasText(name, "'name' must not be empty");
		Assert.hasText(alias, "'alias' must not be empty");
		synchronized (this.aliasMap) {
			if (alias.equals(name)) {
				this.aliasMap.remove(alias);
				if (logger.isDebugEnabled()) {
					logger.debug("Alias definition '" + alias + "' ignored since it points to same name");
				}
			}
			else {
				String registeredName = this.aliasMap.get(alias);
				if (registeredName != null) {
					if (registeredName.equals(name)) {
						// An existing alias - no need to re-register
						return;
					}
					if (!allowAliasOverriding()) {
						throw new IllegalStateException("Cannot define alias '" + alias + "' for name '" +
								name + "': It is already registered for name '" + registeredName + "'.");
					}
					if (logger.isDebugEnabled()) {
						logger.debug("Overriding alias '" + alias + "' definition for registered name '" +
								registeredName + "' with new target name '" + name + "'");
					}
				}
				checkForAliasCircle(name, alias);
				this.aliasMap.put(alias, name);
				if (logger.isTraceEnabled()) {
					logger.trace("Alias definition '" + alias + "' registered for name '" + name + "'");
				}
			}
		}
	}

	protected boolean allowAliasOverriding() {
		return true;
	}
}

checkForAliasCircle 方法在 hasAlias 方法判断 name 为 alias 参数的链式别名,若满足时直接抛出异常;

java 复制代码
public class SimpleAliasRegistry implements AliasRegistry {
	protected void checkForAliasCircle(String name, String alias) {
		if (hasAlias(alias, name)) {
			throw new IllegalStateException("Cannot register alias '" + alias +
					"' for name '" + name + "': Circular reference - '" +
					name + "' is a direct or indirect alias for '" + alias + "' already");
		}
	}

	public boolean hasAlias(String name, String alias) {
		String registeredName = this.aliasMap.get(alias);
		return ObjectUtils.nullSafeEquals(registeredName, name) || (registeredName != null
				&& hasAlias(name, registeredName));
	}
}

1.2 removeAlias 方法

removeAlias 方法在对 aliasMap 属性加锁后直接从 aliasMap 属性中移除 alias 参数关联映射,若其中不存在该映射则直接抛出异常;

java 复制代码
public class SimpleAliasRegistry implements AliasRegistry {
	@Override
	public void removeAlias(String alias) {
		synchronized (this.aliasMap) {
			String name = this.aliasMap.remove(alias);
			if (name == null) {
				throw new IllegalStateException("No alias '" + alias + "' registered");
			}
		}
	}
}

1.3 isAlias 方法

isAlias 方法直接判断 aliasMap 属性中是否存在指定 key;

java 复制代码
public class SimpleAliasRegistry implements AliasRegistry {
	@Override
	public boolean isAlias(String name) {
		return this.aliasMap.containsKey(name);
	}
}

1.4 getAliases 方法

getAliases 方法在锁定 aliasMap 属性后将 name 参数的所有别名,包含链式别名全部保存到 result 变量中同时将其转换为字符串数组并返回;

java 复制代码
public class SimpleAliasRegistry implements AliasRegistry {
	@Override
	public String[] getAliases(String name) {
		List<String> result = new ArrayList<>();
		synchronized (this.aliasMap) {
			retrieveAliases(name, result);
		}
		return StringUtils.toStringArray(result);
	}
}

retrieveAliases 方法用于将 name 参数的链式别名保存到 result 数组中;

java 复制代码
public class SimpleAliasRegistry implements AliasRegistry {
	private void retrieveAliases(String name, List<String> result) {
		this.aliasMap.forEach((alias, registeredName) -> {
			if (registeredName.equals(name)) {
				result.add(alias);
				retrieveAliases(alias, result);
			}
		});
	}
}

2 类方法

2.1 resolveAliases 方法

resolveAliases 方法在通过对 valueResolver 参数进行非空验证后,对 aliasMap 属性的所有元素进行遍历,使用 valueResolver 参数分别对 key 与 value 值进行解析并为 resolvedAlias 与 resolvedName 局部变量进行赋值,在 resolvedAlias 与 resolvedName 变量存在一个为空或这两个变量想等时直接移除当前元素,在 resolvedAlias 变量与 key 别名值不想等时,若 aliasMap 存在 resolvedAlias 变量别名且对应值与 resolvedName 想等时也直接移除 alias 别名,并继续遍历,否则在 resolvedName 与 resolvedAlias 变量通过了循环验证后将 alias 别名映射替换为 resolvedAlias 与 resolvedName 变量映射;而在 resolvedAlias 与 key 别名想等但 resolvedName 变量与 value 值不等时直接将 value 值替换为 resolvedName 变量值;

java 复制代码
public class SimpleAliasRegistry implements AliasRegistry {
	public void resolveAliases(StringValueResolver valueResolver) {
		Assert.notNull(valueResolver, "StringValueResolver must not be null");
		synchronized (this.aliasMap) {
			Map<String, String> aliasCopy = new HashMap<>(this.aliasMap);
			aliasCopy.forEach((alias, registeredName) -> {
				String resolvedAlias = valueResolver.resolveStringValue(alias);
				String resolvedName = valueResolver.resolveStringValue(registeredName);
				if (resolvedAlias == null || resolvedName == null || resolvedAlias.equals(resolvedName)) {
					this.aliasMap.remove(alias);
				}
				else if (!resolvedAlias.equals(alias)) {
					String existingName = this.aliasMap.get(resolvedAlias);
					if (existingName != null) {
						if (existingName.equals(resolvedName)) {
							this.aliasMap.remove(alias);
							return;
						}
						throw new IllegalStateException(
								"Cannot register resolved alias '" + resolvedAlias + "' (original: '" + alias +
								"') for name '" + resolvedName + "': It is already registered for name '" +
								registeredName + "'.");
					}
					checkForAliasCircle(resolvedName, resolvedAlias);
					this.aliasMap.remove(alias);
					this.aliasMap.put(resolvedAlias, resolvedName);
				}
				else if (!registeredName.equals(resolvedName)) {
					this.aliasMap.put(alias, resolvedName);
				}
			});
		}
	}
}

2.2 canonicalName 方法

canonicalName 链式获取 name 映射值已获取 name 对应的原始对象名;

java 复制代码
public class SimpleAliasRegistry implements AliasRegistry {
	public String canonicalName(String name) {
		String canonicalName = name;
		String resolvedName;
		do {
			resolvedName = this.aliasMap.get(canonicalName);
			if (resolvedName != null) {
				canonicalName = resolvedName;
			}
		}
		while (resolvedName != null);
		return canonicalName;
	}
}

三 DefaultSingletonBeanRegistry 类

DefaultSingletonBeanRegistry 类为实现了 SingletonBeanRegistry 接口的共享bean实例的通用注册表;

1 属性

1.1 常量

DefaultSingletonBeanRegistry 类只有一个保存异常最大保存容量的 SUPPRESSED_EXCEPTIONS_LIMIT 常量;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	private static final int SUPPRESSED_EXCEPTIONS_LIMIT = 100;
}

1.2 类属性

singletonObjects、singletonFactories 与 earlySingletonObjects 属性分别用于保存单例对象的映射、缓存单例对象工厂的映射及缓存早期单例对象;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

	private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

	private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);
}

registeredSingletons、singletonsCurrentlyInCreation 与 inCreationCheckExclusions 属性分别保存已注册的单例对象名 Set 集合、正在创建的单例对象名 Set 集合与未通过创建检查的对象名 Set 集合;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	private final Set<String> registeredSingletons = new LinkedHashSet<>(256);

	private final Set<String> singletonsCurrentlyInCreation =
			Collections.newSetFromMap(new ConcurrentHashMap<>(16));

	private final Set<String> inCreationCheckExclusions =
			Collections.newSetFromMap(new ConcurrentHashMap<>(16));
}

suppressedExceptions 属性用于保存未抛出的异常 set 集合;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	@Nullable
	private Set<Exception> suppressedExceptions;
}

singletonsCurrentlyInDestruction 属性标识当前是否正在销毁单例对象;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	private boolean singletonsCurrentlyInDestruction = false;
}

disposableBeans、containedBeanMap、dependentBeanMap 及 dependenciesForBeanMap 属性分别用于保存一次性使用对象映射、对象名与其包含对象名集合映射、对象名及其依赖的对象名集合映射及对象名与依赖其的对象名集合映射;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	private final Map<String, Object> disposableBeans = new LinkedHashMap<>();

	private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<>(16);

	private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<>(64);

	private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<>(64);
}

2 重写方法

2.1 registerSingleton 方法

registerSingleton 方法在通过对 beanName 与 singletonObject 参数进行非空验证后直接对 singletonObjects 属性进行加锁,同时判断 singletonObjects 是否已存在 beanName 参数对应对象,在其存在时直接抛出异常,否则调用 addSingleton 方法将 beanName 与 singletonObject 参数映射添加到 singletonObjects 属性中;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	@Override
	public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
		Assert.notNull(beanName, "Bean name must not be null");
		Assert.notNull(singletonObject, "Singleton object must not be null");
		synchronized (this.singletonObjects) {
			Object oldObject = this.singletonObjects.get(beanName);
			if (oldObject != null) {
				throw new IllegalStateException("Could not register object [" + singletonObject +
						"] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");
			}
			addSingleton(beanName, singletonObject);
		}
	}
}

addSingleton 方法首先也会对 singletonObjects 属性进行加锁,锁定成功后将 beanName 与 singletonObject 参数的映射保存到 singletonObjects 属性中,同时移除 singletonFactories 与 earlySingletonObjects 中 beanName 对应映射值,同时将 beanName 参数保存到 registeredSingletons 属性中。

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	protected void addSingleton(String beanName, Object singletonObject) {
		synchronized (this.singletonObjects) {
			this.singletonObjects.put(beanName, singletonObject);
			this.singletonFactories.remove(beanName);
			this.earlySingletonObjects.remove(beanName);
			this.registeredSingletons.add(beanName);
		}
	}
}

2.2 getSingleton 方法

getSingleton 方法首先尝试从 singletonObjects 中获取 beanName 参数对应对象,若其不为空或 singletonsCurrentlyInCreation 中没有 beanName 元素值时直接返回获取到的对象;否则尝试从 earlySingletonObjects 属性中获取 beanName 参数对应对象,若获取到的对象不为空或 allowEarlyReference 为 false 时直接返回获取到的对象;否则则会对 singletonObjects 属性进行加锁,若 singletonObjects 现在存在 beanName 对象时直接返回该对象,否则在 earlySingletonObjects 存在该对象时返回该属性中对应对象,若还不存在,则会尝试从 singletonFactories 属性中获取对应的对象工厂,若存在则使用获取到的对象工厂创建对象,同时将其与 beanName 参数的映射保存到 earlySingletonObjects 属性中并从 singletonFactories 移除 beanName 参数值,随后返回使用对象工厂创建的对象。

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	@Override
	@Nullable
	public Object getSingleton(String beanName) {
		return getSingleton(beanName, true);
	}

	@Nullable
	protected Object getSingleton(String beanName, boolean allowEarlyReference) {
		Object singletonObject = this.singletonObjects.get(beanName);
		if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
			singletonObject = this.earlySingletonObjects.get(beanName);
			if (singletonObject == null && allowEarlyReference) {
				synchronized (this.singletonObjects) {
					singletonObject = this.singletonObjects.get(beanName);
					if (singletonObject == null) {
						singletonObject = this.earlySingletonObjects.get(beanName);
						if (singletonObject == null) {
							ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
							if (singletonFactory != null) {
								singletonObject = singletonFactory.getObject();
								this.earlySingletonObjects.put(beanName, singletonObject);
								this.singletonFactories.remove(beanName);
							}
						}
					}
				}
			}
		}
		return singletonObject;
	}

	public boolean isSingletonCurrentlyInCreation(String beanName) {
		return this.singletonsCurrentlyInCreation.contains(beanName);
	}
}

2.3 containsSingleton 方法

containsSingleton 方法直接判断 singletonObjects 属性中是否保存 beanName 参数值 key。

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	@Override
	public boolean containsSingleton(String beanName) {
		return this.singletonObjects.containsKey(beanName);
	}
}

2.4 getSingletonNames 方法

getSingletonNames 方法直接将 registeredSingletons 属性转化为字符串数组并返回。

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	@Override
	public String[] getSingletonNames() {
		synchronized (this.singletonObjects) {
			return StringUtils.toStringArray(this.registeredSingletons);
		}
	}
}

2.5 getSingletonCount 方法

getSingletonCount 方法获取 registeredSingletons 属性的元素数量。

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	@Override
	public int getSingletonCount() {
		synchronized (this.singletonObjects) {
			return this.registeredSingletons.size();
		}
	}
}

2.6 getSingletonMutex 方法

getSingletonMutex 方法直接获取 singletonObjects 属性值。

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	@Override
	public final Object getSingletonMutex() {
		return this.singletonObjects;
	}
}

3 类方法

3.1 addSingletonFactory 方法

addSingletonFactory 方法在通过对 singletonFactory 完成了非空验证后,若 singletonFactory 中不包含指定映射时,将 beanName 与 singletonFactory 映射保存到 singletonFactories 属性中同时移除 earlySingletonObjects 属性中的 beanName 元素值,并将 beanName 属性保存到 registeredSingletons 属性中;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
		Assert.notNull(singletonFactory, "Singleton factory must not be null");
		synchronized (this.singletonObjects) {
			if (!this.singletonObjects.containsKey(beanName)) {
				this.singletonFactories.put(beanName, singletonFactory);
				this.earlySingletonObjects.remove(beanName);
				this.registeredSingletons.add(beanName);
			}
		}
	}
}

3.2 getSingleton 方法

getSingleton 方法首先对 beanName 参数进行非空验证,通过后直接对 singletonObjects 属性加锁,同时若 singletonObjects 属性中存在 beanName 对应对象时直接返回该对象,否则在 singletonsCurrentlyInDestruction 属性为 true 时直接抛出异常,之后若 inCreationCheckExclusions 不包含 beanName 参数且 singletonsCurrentlyInCreation 已经存在 beanName 参数时直接抛出异常;若 recordSuppressedExceptions 属性为 null 时将其初始化为空 LinkedHashSet 对象,随后使用 singletonFactory 参数创建对象并保存到 singletonObject 变量中并将 newSingleton 变量值更新为 true;若 singletonFactory 参数创建对象的过程中出现了 IllegalStateException 异常则会尝试将 singletonObject 变量更新为 singletonObjects 属性中对应对象,若其中不存在对应对象直接抛出该异常,否则抛出直接抛出异常,在上述流程执行完成后,无论是否抛出了异常,执行 afterSingletonCreation 方法判断 inCreationCheckExclusions 属性中是否包含 beanName 参数值且 singletonsCurrentlyInCreation 属性是否成功移除 beanName 参数值;最后若 newSingleton 变量为 true,即当前获取到的对象时通过对象工厂新建的则会通过 addSingleton 方法将 beanName 与创建对象映射值保存到 singletonObjects 属性中,最后返回创建或获取到的对象;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
		Assert.notNull(beanName, "Bean name must not be null");
		synchronized (this.singletonObjects) {
			Object singletonObject = this.singletonObjects.get(beanName);
			if (singletonObject == null) {
				if (this.singletonsCurrentlyInDestruction) {
					throw new BeanCreationNotAllowedException(beanName,
							"Singleton bean creation not allowed while singletons of this factory are in destruction " +
							"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
				}
				if (logger.isDebugEnabled()) {
					logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
				}
				beforeSingletonCreation(beanName);
				boolean newSingleton = false;
				boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
				if (recordSuppressedExceptions) {
					this.suppressedExceptions = new LinkedHashSet<>();
				}
				try {
					singletonObject = singletonFactory.getObject();
					newSingleton = true;
				}
				catch (IllegalStateException ex) {
					singletonObject = this.singletonObjects.get(beanName);
					if (singletonObject == null) {
						throw ex;
					}
				}
				catch (BeanCreationException ex) {
					if (recordSuppressedExceptions) {
						for (Exception suppressedException : this.suppressedExceptions) {
							ex.addRelatedCause(suppressedException);
						}
					}
					throw ex;
				}
				finally {
					if (recordSuppressedExceptions) {
						this.suppressedExceptions = null;
					}
					afterSingletonCreation(beanName);
				}
				if (newSingleton) {
					addSingleton(beanName, singletonObject);
				}
			}
			return singletonObject;
		}
	}

	protected void beforeSingletonCreation(String beanName) {
		if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
			throw new BeanCurrentlyInCreationException(beanName);
		}
	}

	protected void afterSingletonCreation(String beanName) {
		if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
			throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
		}
	}
}

3.3 onSuppressedException 方法

onSuppressedException 方法在 suppressedExceptions 属性不为 null 且 suppressedExceptions 的元素量小于 SUPPRESSED_EXCEPTIONS_LIMIT 常量值时把 ex 参数保存到该属性中;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	protected void onSuppressedException(Exception ex) {
		synchronized (this.singletonObjects) {
			if (this.suppressedExceptions != null && this.suppressedExceptions.size() < SUPPRESSED_EXCEPTIONS_LIMIT) {
				this.suppressedExceptions.add(ex);
			}
		}
	}
}

3.4 removeSingleton 方法

removeSingleton 方法移除 singletonObjects、singletonFactories、earlySingletonObjects 及 registeredSingletons 四个属性中的 beanName 参数关联映射元素值;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	protected void removeSingleton(String beanName) {
		synchronized (this.singletonObjects) {
			this.singletonObjects.remove(beanName);
			this.singletonFactories.remove(beanName);
			this.earlySingletonObjects.remove(beanName);
			this.registeredSingletons.remove(beanName);
		}
	}
}

3.5 setCurrentlyInCreation 方法

setCurrentlyInCreation 方法在 inCreation 参数为 true 时,从 inCreationCheckExclusions 中移除 beanName 元素,否则向 inCreationCheckExclusions 属性中添加该参数;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	public void setCurrentlyInCreation(String beanName, boolean inCreation) {
		Assert.notNull(beanName, "Bean name must not be null");
		if (!inCreation) {
			this.inCreationCheckExclusions.add(beanName);
		}
		else {
			this.inCreationCheckExclusions.remove(beanName);
		}
	}
}

3.6 isCurrentlyInCreation 方法

isCurrentlyInCreation 方法在在 inCreationCheckExclusions 属性包含 beanName 参数值时直接返回 false,在 singletonsCurrentlyInCreation 属性中不包含 beanName 参数值时也直接返回 false,否则返回 true;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	public boolean isCurrentlyInCreation(String beanName) {
		Assert.notNull(beanName, "Bean name must not be null");
		return (!this.inCreationCheckExclusions.contains(beanName) && isActuallyInCreation(beanName));
	}

	protected boolean isActuallyInCreation(String beanName) {
		return isSingletonCurrentlyInCreation(beanName);
	}

	public boolean isSingletonCurrentlyInCreation(String beanName) {
		return this.singletonsCurrentlyInCreation.contains(beanName);
	}
}

3.7 registerDisposableBean 方法

registerDisposableBean 方法将 beanName 与 bean 参数映射保存到 disposableBeans 属性中;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	public void registerDisposableBean(String beanName, DisposableBean bean) {
		synchronized (this.disposableBeans) {
			this.disposableBeans.put(beanName, bean);
		}
	}
}

3.8 registerContainedBean 方法

registerContainedBean 方法在将 containedBeanName 成功保存到 containedBeanMap 属性中 containingBeanName 参数对应的 Set 集合中后同时调用 registerDependentBean 方法将参数的依赖关系保存到 dependentBeanMap 与 dependenciesForBeanMap 属性中;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	public void registerContainedBean(String containedBeanName, String containingBeanName) {
		synchronized (this.containedBeanMap) {
			Set<String> containedBeans =
					this.containedBeanMap.computeIfAbsent(containingBeanName, k -> new LinkedHashSet<>(8));
			if (!containedBeans.add(containedBeanName)) {
				return;
			}
		}
		registerDependentBean(containedBeanName, containingBeanName);
	}
}

3.9 registerDependentBean 方法

registerDependentBean 方法首先调用 canonicalName 方法获取 beanName 参数的原始对象名,并在将 dependentBeanName 成功保存到 containedBeanMap 属性中原始对象名对应的 Set 集合中后同时将原始对象名保存到 dependenciesForBeanMap 属性中 dependentBeanName 参数对应的 Set 集合中;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	public void registerDependentBean(String beanName, String dependentBeanName) {
		String canonicalName = canonicalName(beanName);

		synchronized (this.dependentBeanMap) {
			Set<String> dependentBeans =
					this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet<>(8));
			if (!dependentBeans.add(dependentBeanName)) {
				return;
			}
		}

		synchronized (this.dependenciesForBeanMap) {
			Set<String> dependenciesForBean =
					this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new LinkedHashSet<>(8));
			dependenciesForBean.add(canonicalName);
		}
	}
}

3.10 isDependent 方法

isDependent 方法在 alreadySeen 参数中包含 beanName 参数值时直接返回 false,否则尝试从 dependentBeanMap 获取 beanName 参数对应的依赖对象名 set 集合,若不存在直接返回 false,否则若获取到的依赖对象名集合包含 dependentBeanName 参数时直接返回 true,否则将依赖对象名保存到 alreadySeen 参数中递归判断其依赖对象的是否存在 dependentBeanName 对象依赖;若存在直接返回 true,否则返回 false;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	protected boolean isDependent(String beanName, String dependentBeanName) {
		synchronized (this.dependentBeanMap) {
			return isDependent(beanName, dependentBeanName, null);
		}
	}

	private boolean isDependent(String beanName, String dependentBeanName, @Nullable Set<String> alreadySeen) {
		if (alreadySeen != null && alreadySeen.contains(beanName)) {
			return false;
		}
		String canonicalName = canonicalName(beanName);
		Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
		if (dependentBeans == null) {
			return false;
		}
		if (dependentBeans.contains(dependentBeanName)) {
			return true;
		}
		for (String transitiveDependency : dependentBeans) {
			if (alreadySeen == null) {
				alreadySeen = new HashSet<>();
			}
			alreadySeen.add(beanName);
			if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) {
				return true;
			}
		}
		return false;
	}
}

3.11 hasDependentBean 方法

hasDependentBean 方法判断 dependentBeanMap 属性中是否存在 beanName key 值;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	protected boolean hasDependentBean(String beanName) {
		return this.dependentBeanMap.containsKey(beanName);
	}
}

3.12 getDependentBeans 方法

getDependentBeans 方法获取 dependentBeanMap 属性中 beanName 对应的依赖对象名 set 集合数组快照;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	public String[] getDependentBeans(String beanName) {
		Set<String> dependentBeans = this.dependentBeanMap.get(beanName);
		if (dependentBeans == null) {
			return new String[0];
		}
		synchronized (this.dependentBeanMap) {
			return StringUtils.toStringArray(dependentBeans);
		}
	}
}

3.13 getDependenciesForBean 方法

getDependenciesForBean 方法获取 dependenciesForBeanMap 属性中依赖于 beanName 的对象名 set 集合数组快照;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	public String[] getDependenciesForBean(String beanName) {
		Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(beanName);
		if (dependenciesForBean == null) {
			return new String[0];
		}
		synchronized (this.dependenciesForBeanMap) {
			return StringUtils.toStringArray(dependenciesForBean);
		}
	}
}

3.13 destroySingletons 方法

destroySingletons 方法首先将 singletonsCurrentlyInDestruction 属性置为 true,随后调用单参数的 destroySingleton 方法销毁 disposableBeans 属性中所有 key 对应的对象,最后在清空了 containedBeanMap、dependentBeanMap 及 dependenciesForBeanMap 属性后执行 clearSingletonCache 方法清空所有缓存并将 singletonsCurrentlyInDestruction 属性置为 false;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	public void destroySingletons() {
		if (logger.isTraceEnabled()) {
			logger.trace("Destroying singletons in " + this);
		}
		synchronized (this.singletonObjects) {
			this.singletonsCurrentlyInDestruction = true;
		}

		String[] disposableBeanNames;
		synchronized (this.disposableBeans) {
			disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());
		}
		for (int i = disposableBeanNames.length - 1; i >= 0; i--) {
			destroySingleton(disposableBeanNames[i]);
		}

		this.containedBeanMap.clear();
		this.dependentBeanMap.clear();
		this.dependenciesForBeanMap.clear();

		clearSingletonCache();
	}

	protected void clearSingletonCache() {
		synchronized (this.singletonObjects) {
			this.singletonObjects.clear();
			this.singletonFactories.clear();
			this.earlySingletonObjects.clear();
			this.registeredSingletons.clear();
			this.singletonsCurrentlyInDestruction = false;
		}
	}
}

单参数 destroySingleton 方法首先调用 removeSingleton 方法移除 beanName 参数关联对象,同时从 disposableBeans 属性中获取 beanName 映射对象并从该属性中移除该映射值,最后调用双参数 destroyBean 方法销毁获取到 DisposableBean 对象;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	public void destroySingleton(String beanName) {
		removeSingleton(beanName);

		DisposableBean disposableBean;
		synchronized (this.disposableBeans) {
			disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);
		}
		destroyBean(beanName, disposableBean);
	}
}

双参数 destroyBean 方法,首先从 dependentBeanMap 属性中移除 beanName 参数的所有依赖,并在其依赖不为 null 时调用 destroySingleton 方法首先销毁 beanName 的所有依赖对象,之后在 bean 参数不为空时,调用其 destroy 方法销毁该对象,随后调用 destroySingleton 方法销毁 containedBeanMap 属性中 beanName 对象中包含的所有对象并将其从该属性中移除,最后在从 dependentBeanMap 属性中移除所有 beanName 元素的同时从 dependenciesForBeanMap 属性中移除 beanName 对应的映射值;

java 复制代码
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	protected void destroyBean(String beanName, @Nullable DisposableBean bean) {
		Set<String> dependencies;
		synchronized (this.dependentBeanMap) {
			dependencies = this.dependentBeanMap.remove(beanName);
		}
		if (dependencies != null) {
			if (logger.isTraceEnabled()) {
				logger.trace("Retrieved dependent beans for bean '" + beanName + "': " + dependencies);
			}
			for (String dependentBeanName : dependencies) {
				destroySingleton(dependentBeanName);
			}
		}

		if (bean != null) {
			try {
				bean.destroy();
			}
			catch (Throwable ex) {
				if (logger.isWarnEnabled()) {
					logger.warn("Destruction of bean with name '" + beanName + "' threw an exception", ex);
				}
			}
		}

		Set<String> containedBeans;
		synchronized (this.containedBeanMap) {
			containedBeans = this.containedBeanMap.remove(beanName);
		}
		if (containedBeans != null) {
			for (String containedBeanName : containedBeans) {
				destroySingleton(containedBeanName);
			}
		}
		synchronized (this.dependentBeanMap) {
			for (Iterator<Map.Entry<String, Set<String>>> it = this.dependentBeanMap.entrySet().iterator(); it.hasNext();) {
				Map.Entry<String, Set<String>> entry = it.next();
				Set<String> dependenciesToClean = entry.getValue();
				dependenciesToClean.remove(beanName);
				if (dependenciesToClean.isEmpty()) {
					it.remove();
				}
			}
		}
		this.dependenciesForBeanMap.remove(beanName);
	}
}

FactoryBeanRegistrySupport

FactoryBeanRegistrySupport 类单例注册工厂的基类,其只扩展了一个用于缓存对象工厂创建对象的 factoryBeanObjectCache 属性;

java 复制代码
public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {
	private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<>(16);
}

1 重写方法

1.1 removeSingleton 方法

removeSingleton 方法在通过父类的 removeSingleton 方法移除单例对象的同时也会从 factoryBeanObjectCache 缓存中移除该 beanName 参数;

java 复制代码
public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {
	@Override
	protected void removeSingleton(String beanName) {
		synchronized (getSingletonMutex()) {
			super.removeSingleton(beanName);
			this.factoryBeanObjectCache.remove(beanName);
		}
	}
}

1.2 clearSingletonCache 方法

clearSingletonCache 方法在通过父类的 clearSingletonCache 方法移除单例对象的同时也会清空 factoryBeanObjectCache 缓存;

java 复制代码
public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {
	@Override
	protected void clearSingletonCache() {
		synchronized (getSingletonMutex()) {
			super.clearSingletonCache();
			this.factoryBeanObjectCache.clear();
		}
	}
}

2 类方法

2.1 getTypeForFactoryBean 方法

getTypeForFactoryBean 用于获取对象工厂对象的相应类型,值得注意的是在 java 安全策略不为 null,则需要在 java 允许的条件下执行 getObjectType 获取对象类型;

java 复制代码
public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {
	@Nullable
	protected Class<?> getTypeForFactoryBean(FactoryBean<?> factoryBean) {
		try {
			if (System.getSecurityManager() != null) {
				return AccessController.doPrivileged(
						(PrivilegedAction<Class<?>>) factoryBean::getObjectType, getAccessControlContext());
			}
			else {
				return factoryBean.getObjectType();
			}
		}
		catch (Throwable ex) {
			// Thrown from the FactoryBean's getObjectType implementation.
			logger.info("FactoryBean threw exception from getObjectType, despite the contract saying " +
					"that it should return null if the type of its object cannot be determined yet", ex);
			return null;
		}
	}

	protected AccessControlContext getAccessControlContext() {
		return AccessController.getContext();
	}
}

2.2getCachedObjectForFactoryBean 方法

getCachedObjectForFactoryBean 方法用于从缓存中获取指定对象工厂;

java 复制代码
public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {
	@Nullable
	protected Object getCachedObjectForFactoryBean(String beanName) {
		return this.factoryBeanObjectCache.get(beanName);
	}
}

2.3getObjectFromFactoryBean 方法

getObjectFromFactoryBean 方法在 factory 参数不为单例或 beanName 对应对象不是单例时首先调用 doGetObjectFromFactoryBean 使用 factory 对象工厂参数创建对象,同时在 shouldPostProcess 参数为 true 时调用 postProcessObjectFromFactoryBean 方法为对象工厂创建的对象执行后处理(在 FactoryBeanRegistrySupport 类中直接返回传入对象,其具体实现在其子类中重写),并在完成返回创建的对象;否则首先尝试从 factoryBeanObjectCache 缓存中获取缓存对象,若存在直接返回,未获取到时,也是首先调用 doGetObjectFromFactoryBean 方法从factory 参数中创建对象,随后为了防止在 getObject 方法的执行过程中已经完成了对象的后处理,再一次尝试从 factoryBeanObjectCache 获取指定对象,若获取到则也会直接返回获取到的对象,否则若需要进行后处理,则需要判断创建的对象是否还未完成创建,未完成则直接返回未完成创建的对象,完成后则调用 beforeSingletonCreation、postProcessObjectFromFactoryBean 及 afterSingletonCreation 方法对创建对象进行后处理,最后若该对象为单例对象则会将其添加到 factoryBeanObjectCache 缓存中并返回该对象;

java 复制代码
public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {
	protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
		if (factory.isSingleton() && containsSingleton(beanName)) {
			synchronized (getSingletonMutex()) {
				Object object = this.factoryBeanObjectCache.get(beanName);
				if (object == null) {
					object = doGetObjectFromFactoryBean(factory, beanName);
					// Only post-process and store if not put there already during getObject() call above
					// (e.g. because of circular reference processing triggered by custom getBean calls)
					Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
					if (alreadyThere != null) {
						object = alreadyThere;
					}
					else {
						if (shouldPostProcess) {
							if (isSingletonCurrentlyInCreation(beanName)) {
								// Temporarily return non-post-processed object, not storing it yet..
								return object;
							}
							beforeSingletonCreation(beanName);
							try {
								object = postProcessObjectFromFactoryBean(object, beanName);
							}
							catch (Throwable ex) {
								throw new BeanCreationException(beanName,
										"Post-processing of FactoryBean's singleton object failed", ex);
							}
							finally {
								afterSingletonCreation(beanName);
							}
						}
						if (containsSingleton(beanName)) {
							this.factoryBeanObjectCache.put(beanName, object);
						}
					}
				}
				return object;
			}
		}
		else {
			Object object = doGetObjectFromFactoryBean(factory, beanName);
			if (shouldPostProcess) {
				try {
					object = postProcessObjectFromFactoryBean(object, beanName);
				}
				catch (Throwable ex) {
					throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
				}
			}
			return object;
		}
	}

	protected Object postProcessObjectFromFactoryBean(Object object, String beanName) throws BeansException {
		return object;
	}
}

doGetObjectFromFactoryBean 首先使用 factory 参数的 getObject 创建对象,若创建成功则直接返回,否则判断 factory 工厂对象是否还处于创建过程中,若处于创建过程中则会抛出异常,否则创建 NullBean 对象并返回;

java 复制代码
public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {
	private Object doGetObjectFromFactoryBean(FactoryBean<?> factory, String beanName) throws BeanCreationException {
		Object object;
		try {
			if (System.getSecurityManager() != null) {
				AccessControlContext acc = getAccessControlContext();
				try {
					object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc);
				}
				catch (PrivilegedActionException pae) {
					throw pae.getException();
				}
			}
			else {
				object = factory.getObject();
			}
		}
		catch (FactoryBeanNotInitializedException ex) {
			throw new BeanCurrentlyInCreationException(beanName, ex.toString());
		}
		catch (Throwable ex) {
			throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
		}

		// Do not accept a null value for a FactoryBean that's not fully
		// initialized yet: Many FactoryBeans just return null then.
		if (object == null) {
			if (isSingletonCurrentlyInCreation(beanName)) {
				throw new BeanCurrentlyInCreationException(
						beanName, "FactoryBean which is currently in creation returned null from getObject");
			}
			object = new NullBean();
		}
		return object;
	}
}

2.4getFactoryBean 方法

getFactoryBean 方法在 beanInstance 为 FactoryBean 对象时直接将其转化为 FactoryBean 对象并返回,否则抛出异常;

java 复制代码
public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {
	protected FactoryBean<?> getFactoryBean(String beanName, Object beanInstance) throws BeansException {
		if (!(beanInstance instanceof FactoryBean)) {
			throw new BeanCreationException(beanName,
					"Bean instance of type [" + beanInstance.getClass() + "] is not a FactoryBean");
		}
		return (FactoryBean<?>) beanInstance;
	}
}

AbstractBeanFactory 类

AbstractBeanFactory 类为对象工厂的基类,其继承至 FactoryBeanRegistrySupport 类同时实现了 ConfigurableBeanFactory 接口;

1 属性及构造方法

1.1 类属性

AbstractBeanFactory 类为了实现对象工厂的继承,其使用 parentBeanFactory 属性保存其父对象工厂;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Nullable
	private BeanFactory parentBeanFactory;
}

AbstractBeanFactory 类拥有两个类加载器属性,分别为对象解析的 beanClassLoader 属性及临时使用的类加载器 tempClassLoader,其中 beanClassLoader 属性默认为 ClassUtils 类的 getDefaultClassLoader 结果;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Nullable
	private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

	@Nullable
	private ClassLoader tempClassLoader;
}

cacheBeanMetadata 属性用于标识是否需要缓存对象元数据;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	private boolean cacheBeanMetadata = true;
}

beanExpressionResolver、conversionService、propertyEditorRegistrars、customEditors 及 typeConverter 属性分别保存的是对象定义表达式解析器、 作为 PropertyEditor 属性编辑器后备的 ConversionService 类型转换器、PropertyEditor 注册器 set 集合、属性编辑器 PropertyEditor 类型映射及用于重写覆盖 PropertyEditor 对象的 TypeConverter 对象;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Nullable
	private BeanExpressionResolver beanExpressionResolver;

	@Nullable
	private ConversionService conversionService;

	private final Set<PropertyEditorRegistrar> propertyEditorRegistrars = new LinkedHashSet<>(4);

	private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap<>(4);

	@Nullable
	private TypeConverter typeConverter;
}

embeddedValueResolvers 与 beanPostProcessors 分别保存字符串解析器数组及对象后处理器数组;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	private final List<StringValueResolver> embeddedValueResolvers = new CopyOnWriteArrayList<>();

	private final List<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList<>();
}

hasInstantiationAwareBeanPostProcessors 与 hasDestructionAwareBeanPostProcessors 为任意 InstantiationAwareBeanPostProcessor 或 DestructionAwareBeanPostProcessor 两种后处理器实现已注册标识;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	private volatile boolean hasInstantiationAwareBeanPostProcessors;

	private volatile boolean hasDestructionAwareBeanPostProcessors;
}

scopes 属性保存的则是作用域名与对象映射;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	private final Map<String, Scope> scopes = new LinkedHashMap<>(8);
}

securityContextProvider 属性为当前使用的安全策略上下文;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Nullable
	private SecurityContextProvider securityContextProvider;
}

mergedBeanDefinitions、alreadyCreated 与 prototypesCurrentlyInCreation 属性分别为对象名与根对象注册表映射、已完成创建的对象名 set 集合及当前线程与正在创建对象的映射;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	private final Map<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap<>(256);

	private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<>(256));

	private final ThreadLocal<Object> prototypesCurrentlyInCreation =
			new NamedThreadLocal<>("Prototype beans currently in creation");
}

1.2 构造方法

AbstractBeanFactory 类拥有两个不同构造方法,一个直接创建空对象,另一个只会为 parentBeanFactory 参数赋值;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	public AbstractBeanFactory() {
	}

	public AbstractBeanFactory(@Nullable BeanFactory parentBeanFactory) {
		this.parentBeanFactory = parentBeanFactory;
	}
}

2 重写方法

2.1 BeanFactory 接口实现

2.1.1 getBean 方法

所有的 getBean 方法底层都是执行 doGetBean 方法并返回其执行结果;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public Object getBean(String name) throws BeansException {
		return doGetBean(name, null, null, false);
	}

	@Override
	public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
		return doGetBean(name, requiredType, null, false);
	}

	@Override
	public Object getBean(String name, Object... args) throws BeansException {
		return doGetBean(name, null, args, false);
	}

	public <T> T getBean(String name, @Nullable Class<T> requiredType, @Nullable Object... args)
			throws BeansException {

		return doGetBean(name, requiredType, args, false);
	}
}

doGetBean 方法首先调用 transformedBeanName 方法将 name 参数解析为实际对象名,同时尝试使用 getSingleton 方法获取 name 对应的单例对象,若获取到且 args 参数不为 null,则通过 getObjectForBeanInstance 方法为 bean 变量赋值;在获取到的对象为 null 或 args 参数不为 null 时,首先在 beanName 对象还在创建时抛出 BeanCurrentlyInCreationException 异常;

随后若当前对象工厂用于父对象工厂且当前没有 beanName 对应的对象注册表时,即查询的是父对象工厂中的对象,其首先调用 originalBeanName 方法将 name 参数解析为原始对象名,在其拥有 AbstractBeanFactory 的父对象工厂时,直接执行父对象工厂的 doGetBean 工厂获取父对象工厂中对应对象并返回,其余情况直接调用对应父对象工厂的 getBean 方法并返回,其中在 args 或 requiredType 不为空需要传入对应参数用于获取对象;

若 typeCheckOnly 为 false 则直接调用 markBeanAsCreated 方法将 beanName 对应对象标识为已创建,随后通过 getMergedLocalBeanDefinition 方法获取 beanName 对应的对象注册表并通过 checkMergedBeanDefinition 方法对注册表进行验证;验证通过后首先处理依赖对象,其在使用 registerDependentBean 方法注册对象注册表的所有 dependsOn 依赖对象名时同时依次调用 getBean 方法先创建其所有依赖对象;

在完成了对依赖对象处理后,进一步对作用域进行处理,在其为单例对象时,使用 createBean 方法通过 mbd 对象注册表创建对象或从缓存中获取对象并执行 getObjectForBeanInstance 方法对获取到的对象进行进一步处理并将处理结果保存到 bean 变量中;在对象为原型模式时首先调用 beforePrototypeCreation 方法将 beanName 值保存到 prototypesCurrentlyInCreation 属性中,并在通过 createBean 使用对象注册表创建对象后使用 afterPrototypeCreation 将 beanName 参数从 prototypesCurrentlyInCreation 属性中移除,最后也会通过 getObjectForBeanInstance 方法对创建对象进行处理并将处理后的值保存到 bean 变量中;若为其他自定义作用域时,若 mbd 未设置作用域时直接抛出异常,否则从 scopes 属性中获取其作用域名对应的作用域对象,若为空直接抛出异常,随后使用 beanName 与使用 beforePrototypeCreation + createBean + afterPrototypeCreation 方法实现的对象工厂对象执行作用域对象的 get 方法获取或创建对象,最后也是通过 getObjectForBeanInstance 方法对创建对象进行处理并赋值给 bean 变量;若在对象创建过程中出现了 BeansException 异常,则会在执行 cleanupAfterBeanCreationFailure 方法先清空 alreadyCreated 属性再抛出异常;

最后 requiredType 参数为 null 或 bean 变量不为 requiredType 类型对象,则直接返回 bean 变量值,否则将会使用 TypeConverter 类型转换器的 convertIfNecessary 方法尝试将 bean 转化为 requiredType 类型对象,若成功转换则直接返回转换值,否则抛出 BeanNotOfRequiredTypeException 异常;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	protected <T> T doGetBean(
			String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
			throws BeansException {

		String beanName = transformedBeanName(name);
		Object bean;

		// Eagerly check singleton cache for manually registered singletons.
		Object sharedInstance = getSingleton(beanName);
		if (sharedInstance != null && args == null) {
			if (logger.isTraceEnabled()) {
				if (isSingletonCurrentlyInCreation(beanName)) {
					logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
							"' that is not fully initialized yet - a consequence of a circular reference");
				}
				else {
					logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
				}
			}
			bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
		}

		else {
			// Fail if we're already creating this bean instance:
			// We're assumably within a circular reference.
			if (isPrototypeCurrentlyInCreation(beanName)) {
				throw new BeanCurrentlyInCreationException(beanName);
			}

			// Check if bean definition exists in this factory.
			BeanFactory parentBeanFactory = getParentBeanFactory();
			if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
				// Not found -> check parent.
				String nameToLookup = originalBeanName(name);
				if (parentBeanFactory instanceof AbstractBeanFactory) {
					return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
							nameToLookup, requiredType, args, typeCheckOnly);
				}
				else if (args != null) {
					// Delegation to parent with explicit args.
					return (T) parentBeanFactory.getBean(nameToLookup, args);
				}
				else if (requiredType != null) {
					// No args -> delegate to standard getBean method.
					return parentBeanFactory.getBean(nameToLookup, requiredType);
				}
				else {
					return (T) parentBeanFactory.getBean(nameToLookup);
				}
			}

			if (!typeCheckOnly) {
				markBeanAsCreated(beanName);
			}

			try {
				RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
				checkMergedBeanDefinition(mbd, beanName, args);

				// Guarantee initialization of beans that the current bean depends on.
				String[] dependsOn = mbd.getDependsOn();
				if (dependsOn != null) {
					for (String dep : dependsOn) {
						if (isDependent(beanName, dep)) {
							throw new BeanCreationException(mbd.getResourceDescription(), beanName,
									"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
						}
						registerDependentBean(dep, beanName);
						try {
							getBean(dep);
						}
						catch (NoSuchBeanDefinitionException ex) {
							throw new BeanCreationException(mbd.getResourceDescription(), beanName,
									"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
						}
					}
				}

				// Create bean instance.
				if (mbd.isSingleton()) {
					sharedInstance = getSingleton(beanName, () -> {
						try {
							return createBean(beanName, mbd, args);
						}
						catch (BeansException ex) {
							// Explicitly remove instance from singleton cache: It might have been put there
							// eagerly by the creation process, to allow for circular reference resolution.
							// Also remove any beans that received a temporary reference to the bean.
							destroySingleton(beanName);
							throw ex;
						}
					});
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}

				else if (mbd.isPrototype()) {
					// It's a prototype -> create a new instance.
					Object prototypeInstance = null;
					try {
						beforePrototypeCreation(beanName);
						prototypeInstance = createBean(beanName, mbd, args);
					}
					finally {
						afterPrototypeCreation(beanName);
					}
					bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
				}

				else {
					String scopeName = mbd.getScope();
					if (!StringUtils.hasLength(scopeName)) {
						throw new IllegalStateException("No scope name defined for bean '" + beanName + "'");
					}
					Scope scope = this.scopes.get(scopeName);
					if (scope == null) {
						throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
					}
					try {
						Object scopedInstance = scope.get(beanName, () -> {
							beforePrototypeCreation(beanName);
							try {
								return createBean(beanName, mbd, args);
							}
							finally {
								afterPrototypeCreation(beanName);
							}
						});
						bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
					}
					catch (IllegalStateException ex) {
						throw new BeanCreationException(beanName,
								"Scope '" + scopeName + "' is not active for the current thread; consider " +
								"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
								ex);
					}
				}
			}
			catch (BeansException ex) {
				cleanupAfterBeanCreationFailure(beanName);
				throw ex;
			}
		}

		// Check if required type matches the type of the actual bean instance.
		if (requiredType != null && !requiredType.isInstance(bean)) {
			try {
				T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
				if (convertedBean == null) {
					throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
				}
				return convertedBean;
			}
			catch (TypeMismatchException ex) {
				if (logger.isTraceEnabled()) {
					logger.trace("Failed to convert bean '" + name + "' to required type '" +
							ClassUtils.getQualifiedName(requiredType) + "'", ex);
				}
				throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
			}
		}
		return (T) bean;
	}

	protected abstract boolean containsBeanDefinition(String beanName);

	protected abstract Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException;
}

getObjectForBeanInstance 方法首先通过 isFactoryDereference 方法判断 name 参数是否为对象工厂名,若满足则会将 mbd 参数的 isFactoryBean 属性置为 true 表明该元数据为对象工厂并返回 beanInstance 参数;否则在 beanInstance 不为 FactoryBean 对象时也会直接返回该参数值;随后在 mbd 元数据不为 null 时也会将其 isFactoryBean 属性置为 true 否则继续尝试执行 getCachedObjectForFactoryBean 方法从 factoryBeanObjectCache 缓存中获取 beanName 对应对象为 object 变量进行赋值,若 object 变量为 null,之后若未从缓存获取或 mbd 不为合成对象时,将会通过 getObjectFromFactoryBean 方法从工厂对象中创建对象并返回。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	protected Object getObjectForBeanInstance(
			Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {

		// Don't let calling code try to dereference the factory if the bean isn't a factory.
		if (BeanFactoryUtils.isFactoryDereference(name)) {
			if (beanInstance instanceof NullBean) {
				return beanInstance;
			}
			if (!(beanInstance instanceof FactoryBean)) {
				throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
			}
			if (mbd != null) {
				mbd.isFactoryBean = true;
			}
			return beanInstance;
		}

		// Now we have the bean instance, which may be a normal bean or a FactoryBean.
		// If it's a FactoryBean, we use it to create a bean instance, unless the
		// caller actually wants a reference to the factory.
		if (!(beanInstance instanceof FactoryBean)) {
			return beanInstance;
		}

		Object object = null;
		if (mbd != null) {
			mbd.isFactoryBean = true;
		}
		else {
			object = getCachedObjectForFactoryBean(beanName);
		}
		if (object == null) {
			// Return bean instance from factory.
			FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
			// Caches object obtained from FactoryBean if it is a singleton.
			if (mbd == null && containsBeanDefinition(beanName)) {
				mbd = getMergedLocalBeanDefinition(beanName);
			}
			boolean synthetic = (mbd != null && mbd.isSynthetic());
			object = getObjectFromFactoryBean(factory, beanName, !synthetic);
		}
		return object;
	}
}

beforePrototypeCreation 方法在 prototypesCurrentlyInCreation 属性中当前线程没有正在创建的原型模式对象时直接将 beanName 参数保存到 prototypesCurrentlyInCreation 属性中,否则在 prototypesCurrentlyInCreation 属性对应值为字符串时,将其值更新为 HashSet 对象并将之前值与 beanName 参数保存到该集合中;否则将 beanName 参数值添加到该属性中;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	protected void beforePrototypeCreation(String beanName) {
		Object curVal = this.prototypesCurrentlyInCreation.get();
		if (curVal == null) {
			this.prototypesCurrentlyInCreation.set(beanName);
		}
		else if (curVal instanceof String) {
			Set<String> beanNameSet = new HashSet<>(2);
			beanNameSet.add((String) curVal);
			beanNameSet.add(beanName);
			this.prototypesCurrentlyInCreation.set(beanNameSet);
		}
		else {
			Set<String> beanNameSet = (Set<String>) curVal;
			beanNameSet.add(beanName);
		}
	}
}
2.1.2 containsBean 方法

containsBean 方法用于判断当前对象工厂或父对象工厂是否拥有名为 name 对象;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public boolean containsBean(String name) {
		String beanName = transformedBeanName(name);
		if (containsSingleton(beanName) || containsBeanDefinition(beanName)) {
			return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(name));
		}
		// Not found -> check parent.
		BeanFactory parentBeanFactory = getParentBeanFactory();
		return (parentBeanFactory != null && parentBeanFactory.containsBean(originalBeanName(name)));
	}
}
2.1.3 isSingleton 方法

isSingleton 方法用于指定对象是否为单例对象,其首先尝试通过 getSingleton 方法获取 name 对应的单例对象,若获取到的对象不为空且其不为工厂对象时直接返回 name 是否不为对象工厂封装名,在对象不为空且为工厂对象时名,则会返回 name 是否为工厂对象名或该对象是否为单例对象;为获取到对象时,在父对象工厂不为空且当前工厂中没有对应对象注册表时,直接返回 name 是否在父对象工厂中为单例对象;之后通过 getMergedLocalBeanDefinition 方法获取 name 对应的 RootBeanDefinition 对象注册表对象,若其不为单例对象直接返回 false,在其为工厂对象且不为对象工厂时,则会返回 name 是否不为对象工厂对象名,否则在 name 是为对象工厂对象名直接返回 true,否则返回 FACTORY_BEAN_PREFIX 与原始对象名拼接的字符串对应对象是否为单例对象;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
		String beanName = transformedBeanName(name);

		Object beanInstance = getSingleton(beanName, false);
		if (beanInstance != null) {
			if (beanInstance instanceof FactoryBean) {
				return (BeanFactoryUtils.isFactoryDereference(name) || ((FactoryBean<?>) beanInstance).isSingleton());
			}
			else {
				return !BeanFactoryUtils.isFactoryDereference(name);
			}
		}

		// No singleton instance found -> check bean definition.
		BeanFactory parentBeanFactory = getParentBeanFactory();
		if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
			// No bean definition found in this factory -> delegate to parent.
			return parentBeanFactory.isSingleton(originalBeanName(name));
		}

		RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);

		// In case of FactoryBean, return singleton status of created object if not a dereference.
		if (mbd.isSingleton()) {
			if (isFactoryBean(beanName, mbd)) {
				if (BeanFactoryUtils.isFactoryDereference(name)) {
					return true;
				}
				FactoryBean<?> factoryBean = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
				return factoryBean.isSingleton();
			}
			else {
				return !BeanFactoryUtils.isFactoryDereference(name);
			}
		}
		else {
			return false;
		}
	}
}
2.1.4 isPrototype 方法

isPrototype 方法首先在父对象工厂不为空且当前工厂中没有对应对象注册表时,直接返回 name 是否在父对象工厂中为原型模式对象,否则在 name 对应的对象注册表作用域为原型模式时,则返回 name 是否不为对象工厂对象名或对象注册表是否为对象工厂对象;之后若 name 参数值不为对象工厂类名或其对应注册表不为对象工厂时直接返回 false,否则会通过 getBean 方法获取 name 对应的工厂对象,并判断其对象工厂是否为原型模式的 SmartFactoryBean 对象或不为单例对象工厂。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public boolean isPrototype(String name) throws NoSuchBeanDefinitionException {
		String beanName = transformedBeanName(name);

		BeanFactory parentBeanFactory = getParentBeanFactory();
		if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
			// No bean definition found in this factory -> delegate to parent.
			return parentBeanFactory.isPrototype(originalBeanName(name));
		}

		RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
		if (mbd.isPrototype()) {
			// In case of FactoryBean, return singleton status of created object if not a dereference.
			return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName, mbd));
		}

		// Singleton or scoped - not a prototype.
		// However, FactoryBean may still produce a prototype object...
		if (BeanFactoryUtils.isFactoryDereference(name)) {
			return false;
		}
		if (isFactoryBean(beanName, mbd)) {
			FactoryBean<?> fb = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
			if (System.getSecurityManager() != null) {
				return AccessController.doPrivileged(
						(PrivilegedAction<Boolean>) () ->
								((fb instanceof SmartFactoryBean && ((SmartFactoryBean<?>) fb).isPrototype()) ||
										!fb.isSingleton()),
						getAccessControlContext());
			}
			else {
				return ((fb instanceof SmartFactoryBean && ((SmartFactoryBean<?>) fb).isPrototype()) ||
						!fb.isSingleton());
			}
		}
		else {
			return false;
		}
	}
}
2.1.5 isTypeMatch 方法

isTypeMatch 方法首先将 name 是否为对象工厂对象名保存到 isFactoryDereference 变量中同时通过 getSingleton 方法尝试获取 name 对应的单例对象,若其不为空,在该对象为对象工厂对象且 name 不为对象工厂对象名时,直接返回该对象工厂对象关联类型是否为 typeToMatch 参数类型,在该对象为对象工厂对象且 name 为对象工厂对象名时,则直接判断该对象是否为 typeToMatch 参数类型对象;在获取到的单例对象不为对象工厂对象且 name 不为对象工厂对象名时,若该对象为 typeToMatch 参数类型对象时直接返回 true;typeToMatch 参数为泛型且当前对象工厂拥有 name 对应的对象注册表时,在其注册表目标类型不为空且不等于对象的实际类型时,在 typeToMatch 参数的解析类型不为获取对象类型时直接返回 false,在 typeToMatch 参数中的类型为注册表对应参数的父类时直接返回 true,随后返回 typeToMatch 参数是否为 mbd 目标类型父类;若获取到的单例对象不为对象工厂对象且 name 不为对象工厂对象名但不满足上述其他条件时直接返回 false;

在获取到的单例对象为 null 但当前对象工厂拥有 name 对应单例对象但没有对应的对象注册表,即当前 name 注册的是 Nullable 空单例对象时直接返回 false;之后若父对象工厂不为空但没有对应的对象注册表时,直接返回父对象工厂的 isTypeMatch 方法并返回;随后则对对象注册表进行搜索,其在 typeToMatch 参数的 resolve 方法执行结果为空或 FactoryBean 类型对象时,将 typesToMatch 变量初始化为 FactoryBean 单参数 Class 对象数组,否则将其初始化 FactoryBean 类型与解析结果数组,同时分别将 mbd 与 dbd 局部变量值更新为对应对象注册表与其内不对象注册表存储器;在 name 不为对象工厂对象名、dbd 不为 null 且 mbd 为对象工厂,若该对象注册表不为延迟初始化或 allowFactoryBeanInit 为 true 时,通过 getMergedBeanDefinition 方法获取 dbd 对应的对象注册表,在该内部对象注册表属性不为 FactoryBean 对象时将 predictedType 变量更新为 mbd 内部对象注册表类型;之后若 predictedType 变量为 null 且 mbd 变量对应的预测类型也为 null 时直接返回 false;若 mbd 变量对应类型为 FactoryBean 时,同时满足获取到的对象为 null 与 name 不为对象工厂对象名两个条件时,尝试使用 getTypeForFactoryBean 方法从 mbd 中获取工厂对象对应类型并保存到 beanType 变量中,并在该结果的 resolve 结果为 null 时直接返回 false,在 mbd 变量对应类型不为 FactoryBean 且 name 不为对象工厂对象名时,进一步使用 beanName 参数、mbd 对象注册表及 FactoryBean Class 对象执行 predictBeanType 方法来重新获取原始类型来为 prediictedType 变量进行赋值,若其结果为 FactoryBean 的子类则直接返回 false;之后在 beanType 属性为 null,即之前的 predictedType 属性不为对象工厂时,在 mbd 目标类型与 predictedType 变量时,将 beanType 更新为 mbd 对应的属性值;最后若 beanType 变量还是为 null 则返回 predictedType 属性是否为 typeToMatch 的子类,否则返回 beanType 是否为 typeToMatch 的子类;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException {
		return isTypeMatch(name, typeToMatch, true);
	}

	protected boolean isTypeMatch(String name, ResolvableType typeToMatch, boolean allowFactoryBeanInit)
			throws NoSuchBeanDefinitionException {

		String beanName = transformedBeanName(name);
		boolean isFactoryDereference = BeanFactoryUtils.isFactoryDereference(name);

		// Check manually registered singletons.
		Object beanInstance = getSingleton(beanName, false);
		if (beanInstance != null && beanInstance.getClass() != NullBean.class) {
			if (beanInstance instanceof FactoryBean) {
				if (!isFactoryDereference) {
					Class<?> type = getTypeForFactoryBean((FactoryBean<?>) beanInstance);
					return (type != null && typeToMatch.isAssignableFrom(type));
				}
				else {
					return typeToMatch.isInstance(beanInstance);
				}
			}
			else if (!isFactoryDereference) {
				if (typeToMatch.isInstance(beanInstance)) {
					// Direct match for exposed instance?
					return true;
				}
				else if (typeToMatch.hasGenerics() && containsBeanDefinition(beanName)) {
					// Generics potentially only match on the target class, not on the proxy...
					RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
					Class<?> targetType = mbd.getTargetType();
					if (targetType != null && targetType != ClassUtils.getUserClass(beanInstance)) {
						// Check raw class match as well, making sure it's exposed on the proxy.
						Class<?> classToMatch = typeToMatch.resolve();
						if (classToMatch != null && !classToMatch.isInstance(beanInstance)) {
							return false;
						}
						if (typeToMatch.isAssignableFrom(targetType)) {
							return true;
						}
					}
					ResolvableType resolvableType = mbd.targetType;
					if (resolvableType == null) {
						resolvableType = mbd.factoryMethodReturnType;
					}
					return (resolvableType != null && typeToMatch.isAssignableFrom(resolvableType));
				}
			}
			return false;
		}
		else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
			// null instance registered
			return false;
		}

		// No singleton instance found -> check bean definition.
		BeanFactory parentBeanFactory = getParentBeanFactory();
		if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
			// No bean definition found in this factory -> delegate to parent.
			return parentBeanFactory.isTypeMatch(originalBeanName(name), typeToMatch);
		}

		// Retrieve corresponding bean definition.
		RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
		BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();

		// Setup the types that we want to match against
		Class<?> classToMatch = typeToMatch.resolve();
		if (classToMatch == null) {
			classToMatch = FactoryBean.class;
		}
		Class<?>[] typesToMatch = (FactoryBean.class == classToMatch ?
				new Class<?>[] {classToMatch} : new Class<?>[] {FactoryBean.class, classToMatch});


		// Attempt to predict the bean type
		Class<?> predictedType = null;

		// We're looking for a regular reference but we're a factory bean that has
		// a decorated bean definition. The target bean should be the same type
		// as FactoryBean would ultimately return.
		if (!isFactoryDereference && dbd != null && isFactoryBean(beanName, mbd)) {
			// We should only attempt if the user explicitly set lazy-init to true
			// and we know the merged bean definition is for a factory bean.
			if (!mbd.isLazyInit() || allowFactoryBeanInit) {
				RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
				Class<?> targetType = predictBeanType(dbd.getBeanName(), tbd, typesToMatch);
				if (targetType != null && !FactoryBean.class.isAssignableFrom(targetType)) {
					predictedType = targetType;
				}
			}
		}

		// If we couldn't use the target type, try regular prediction.
		if (predictedType == null) {
			predictedType = predictBeanType(beanName, mbd, typesToMatch);
			if (predictedType == null) {
				return false;
			}
		}

		// Attempt to get the actual ResolvableType for the bean.
		ResolvableType beanType = null;

		// If it's a FactoryBean, we want to look at what it creates, not the factory class.
		if (FactoryBean.class.isAssignableFrom(predictedType)) {
			if (beanInstance == null && !isFactoryDereference) {
				beanType = getTypeForFactoryBean(beanName, mbd, allowFactoryBeanInit);
				predictedType = beanType.resolve();
				if (predictedType == null) {
					return false;
				}
			}
		}
		else if (isFactoryDereference) {
			// Special case: A SmartInstantiationAwareBeanPostProcessor returned a non-FactoryBean
			// type but we nevertheless are being asked to dereference a FactoryBean...
			// Let's check the original bean class and proceed with it if it is a FactoryBean.
			predictedType = predictBeanType(beanName, mbd, FactoryBean.class);
			if (predictedType == null || !FactoryBean.class.isAssignableFrom(predictedType)) {
				return false;
			}
		}

		// We don't have an exact type but if bean definition target type or the factory
		// method return type matches the predicted type then we can use that.
		if (beanType == null) {
			ResolvableType definedType = mbd.targetType;
			if (definedType == null) {
				definedType = mbd.factoryMethodReturnType;
			}
			if (definedType != null && definedType.resolve() == predictedType) {
				beanType = definedType;
			}
		}

		// If we have a bean type use it so that generics are considered
		if (beanType != null) {
			return typeToMatch.isAssignableFrom(beanType);
		}

		// If we don't have a bean type, fallback to the predicted type
		return typeToMatch.isAssignableFrom(predictedType);
	}

	@Override
	public boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException {
		return isTypeMatch(name, ResolvableType.forRawClass(typeToMatch));
	}
}
2.1.6 getType 方法

getType 方法在当前对象工厂拥有 name 参数对应单例对象时,直接返回其对应类型值;在其拥有父对象工厂且当前工厂中没有对应的对象注册表时,直接尝试使用 getType 方法获取其对应的类型值;否则则尝试获取 name 对应注册表的修饰对象类型值,在为获取到其内部修饰对象类型或其为工厂对象时,则会返回其注册表对象对应类型值;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	@Nullable
	public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
		return getType(name, true);
	}

	@Override
	@Nullable
	public Class<?> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException {
		String beanName = transformedBeanName(name);

		// Check manually registered singletons.
		Object beanInstance = getSingleton(beanName, false);
		if (beanInstance != null && beanInstance.getClass() != NullBean.class) {
			if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
				return getTypeForFactoryBean((FactoryBean<?>) beanInstance);
			}
			else {
				return beanInstance.getClass();
			}
		}

		// No singleton instance found -> check bean definition.
		BeanFactory parentBeanFactory = getParentBeanFactory();
		if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
			// No bean definition found in this factory -> delegate to parent.
			return parentBeanFactory.getType(originalBeanName(name));
		}

		RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);

		// Check decorated bean definition, if any: We assume it'll be easier
		// to determine the decorated bean's type than the proxy's type.
		BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
		if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {
			RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
			Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd);
			if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) {
				return targetClass;
			}
		}

		Class<?> beanClass = predictBeanType(beanName, mbd);

		// Check bean class whether we're dealing with a FactoryBean.
		if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) {
			if (!BeanFactoryUtils.isFactoryDereference(name)) {
				// If it's a FactoryBean, we want to look at what it creates, not at the factory class.
				return getTypeForFactoryBean(beanName, mbd, allowFactoryBeanInit).resolve();
			}
			else {
				return beanClass;
			}
		}
		else {
			return (!BeanFactoryUtils.isFactoryDereference(name) ? beanClass : null);
		}
	}
}
2.1.7 getAliases 方法

getAliases 方法首先使用 transformedBeanName 方法将 name 参数获取原始对象名,同时将其值保存到 fullBeanName 变量中,若 name 参数为工厂对象名时,会将 fullBeanName 变量值更新为对象工厂名前缀 + 原始对象名;若 fullBeanName 变量值与 name 参数值不等时,直接将该变量值添加到需要返回的别名数组中;随后将通过父类的 getAliases 方法获取原始类名对应的别名数组中不与 name 参数相等的元素值全保存到需返回的别名数组中;最后若当前不包含原始类名对应的单例对象与注册表且在父对象工厂不为空时,将父类中 fullBeanName 变量对应别名数组全保存到需返回的别名数组中;最后将上述获取到的别名数组返回。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public String[] getAliases(String name) {
		String beanName = transformedBeanName(name);
		List<String> aliases = new ArrayList<>();
		boolean factoryPrefix = name.startsWith(FACTORY_BEAN_PREFIX);
		String fullBeanName = beanName;
		if (factoryPrefix) {
			fullBeanName = FACTORY_BEAN_PREFIX + beanName;
		}
		if (!fullBeanName.equals(name)) {
			aliases.add(fullBeanName);
		}
		String[] retrievedAliases = super.getAliases(beanName);
		String prefix = factoryPrefix ? FACTORY_BEAN_PREFIX : "";
		for (String retrievedAlias : retrievedAliases) {
			String alias = prefix + retrievedAlias;
			if (!alias.equals(name)) {
				aliases.add(alias);
			}
		}
		if (!containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
			BeanFactory parentBeanFactory = getParentBeanFactory();
			if (parentBeanFactory != null) {
				aliases.addAll(Arrays.asList(parentBeanFactory.getAliases(fullBeanName)));
			}
		}
		return StringUtils.toStringArray(aliases);
	}
}

2.2 HierarchicalBeanFactory 接口实现

2.2.1 getParentBeanFactory 方法

getParentBeanFactory 方法直接返回 parentBeanFactory 属性值;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	@Nullable
	public BeanFactory getParentBeanFactory() {
		return this.parentBeanFactory;
	}
}
2.2.2 containsLocalBean 方法

containsLocalBean 方法在当前对象工厂中拥有 name 参数对应的单例对象或对象注册表且name参数与对应对象是否为对象工厂时相统一时返回 true;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public boolean containsLocalBean(String name) {
		String beanName = transformedBeanName(name);
		return ((containsSingleton(beanName) || containsBeanDefinition(beanName)) &&
				(!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName)));
	}
}

2.3 ConfigurableBeanFactory 接口实现

2.3.1 setParentBeanFactory 方法

setParentBeanFactory 方法在 parentBeanFactory 属性不为 null 且与 parentBeanFactory 参数不一致时直接抛出 IllegalStateException 异常,同时在 parentBeanFactory 参数就是当前对象时也会抛出 IllegalStateException 异常,最后在通过验证后将 parentBeanFactory 属性更新为 parentBeanFactory 参数值;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public void setParentBeanFactory(@Nullable BeanFactory parentBeanFactory) {
		if (this.parentBeanFactory != null && this.parentBeanFactory != parentBeanFactory) {
			throw new IllegalStateException("Already associated with parent BeanFactory: " + this.parentBeanFactory);
		}
		if (this == parentBeanFactory) {
			throw new IllegalStateException("Cannot set parent bean factory to self");
		}
		this.parentBeanFactory = parentBeanFactory;
	}
}
2.3.2 beanClassLoader 方法

setBeanClassLoader 方法在 beanClassLoader 参数不为空将其保存到 beanClassLoader 属性中,否则将 beanClassLoader 属性更新为默认类加载器;而 getBeanClassLoader 方法则是直接返回 beanClassLoader 属性值。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public void setBeanClassLoader(@Nullable ClassLoader beanClassLoader) {
		this.beanClassLoader = (beanClassLoader != null ? beanClassLoader : ClassUtils.getDefaultClassLoader());
	}

	@Override
	@Nullable
	public ClassLoader getBeanClassLoader() {
		return this.beanClassLoader;
	}
}
2.3.3 tempClassLoader 方法

setTempClassLoader 与 getTempClassLoader 方法分别直接设置和获取 tempClassLoader 属性值。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public void setTempClassLoader(@Nullable ClassLoader tempClassLoader) {
		this.tempClassLoader = tempClassLoader;
	}

	@Override
	@Nullable
	public ClassLoader getTempClassLoader() {
		return this.tempClassLoader;
	}
}
2.3.4 cacheBeanMetadata 方法

setCacheBeanMetadata 与 isCacheBeanMetadata 方法分别直接设置和获取 cacheBeanMetadata 属性值。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public void setCacheBeanMetadata(boolean cacheBeanMetadata) {
		this.cacheBeanMetadata = cacheBeanMetadata;
	}

	@Override
	public boolean isCacheBeanMetadata() {
		return this.cacheBeanMetadata;
	}
}
2.3.5 beanExpressionResolver 方法

setBeanExpressionResolver 与 getBeanExpressionResolver 方法分别直接设置和获取 beanExpressionResolver 属性值。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public void setBeanExpressionResolver(@Nullable BeanExpressionResolver resolver) {
		this.beanExpressionResolver = resolver;
	}

	@Override
	@Nullable
	public BeanExpressionResolver getBeanExpressionResolver() {
		return this.beanExpressionResolver;
	}
}
2.3.6 conversionService 方法

setConversionService 与 getConversionService 方法分别直接设置和获取 conversionService 属性值。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public void setConversionService(@Nullable ConversionService conversionService) {
		this.conversionService = conversionService;
	}

	@Override
	@Nullable
	public ConversionService getConversionService() {
		return this.conversionService;
	}
}
2.3.7 propertyEditorRegistrars 方法

addPropertyEditorRegistrar 与 getPropertyEditorRegistrars 方法分别直接设置和获取 propertyEditorRegistrars 属性值。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar) {
		Assert.notNull(registrar, "PropertyEditorRegistrar must not be null");
		this.propertyEditorRegistrars.add(registrar);
	}

	public Set<PropertyEditorRegistrar> getPropertyEditorRegistrars() {
		return this.propertyEditorRegistrars;
	}
}
2.3.8 customEditors 方法

registerCustomEditor 方法在通过了对 requiredType 与 propertyEditorClass 参数的非空验证后,将 requiredType 与 propertyEditorClass 参数的映射值保存到 customEditors 属性中;copyRegisteredEditorsTo 方法则直接调用 registerCustomEditors 方法将 registry 参数中的所有属性编辑器映射全保存到 customEditors 属性中;getCustomEditors 方法则用于获取该属性值。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass) {
		Assert.notNull(requiredType, "Required type must not be null");
		Assert.notNull(propertyEditorClass, "PropertyEditor class must not be null");
		this.customEditors.put(requiredType, propertyEditorClass);
	}

	@Override
	public void copyRegisteredEditorsTo(PropertyEditorRegistry registry) {
		registerCustomEditors(registry);
	}

	public Map<Class<?>, Class<? extends PropertyEditor>> getCustomEditors() {
		return this.customEditors;
	}
}
2.3.9 typeConverter 方法

setTypeConverter 与 getCustomTypeConverter 方法分别直接设置和获取 typeConverter 属性值。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public void setTypeConverter(TypeConverter typeConverter) {
		this.typeConverter = typeConverter;
	}

	@Nullable
	protected TypeConverter getCustomTypeConverter() {
		return this.typeConverter;
	}
}

getTypeConverter 方法在 typeConverter 属性不为空时直接返回该属性值,否则使用 getConversionService 方法执行结果创建 SimpleTypeConverter 对象并调用 registerCustomEditors 方法将其注册到当前对象中同时返回创建的 SimpleTypeConverter 对象值;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public TypeConverter getTypeConverter() {
		TypeConverter customConverter = getCustomTypeConverter();
		if (customConverter != null) {
			return customConverter;
		}
		else {
			// Build default TypeConverter, registering custom editors.
			SimpleTypeConverter typeConverter = new SimpleTypeConverter();
			typeConverter.setConversionService(getConversionService());
			registerCustomEditors(typeConverter);
			return typeConverter;
		}
	}
}
2.3.10 embeddedValueResolvers 方法

addEmbeddedValueResolver 方法在通过了对 valueResolver 参数的非空验证后,将其添加到 embeddedValueResolvers 属性中;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public void addEmbeddedValueResolver(StringValueResolver valueResolver) {
		Assert.notNull(valueResolver, "StringValueResolver must not be null");
		this.embeddedValueResolvers.add(valueResolver);
	}
}

hasEmbeddedValueResolver 方法返回 embeddedValueResolvers 属性是否不为空;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public boolean hasEmbeddedValueResolver() {
		return !this.embeddedValueResolvers.isEmpty();
	}
}

resolveEmbeddedValue 方法在 value 参数为 null 时直接返回 null,否则按 embeddedValueResolvers 属性元素顺序使用 resolveStringValue 方法依次迭代解析 value,若解析过程出现了 null 值则直接返回 null,否则在迭代完成后返回迭代结果;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	@Nullable
	public String resolveEmbeddedValue(@Nullable String value) {
		if (value == null) {
			return null;
		}
		String result = value;
		for (StringValueResolver resolver : this.embeddedValueResolvers) {
			result = resolver.resolveStringValue(result);
			if (result == null) {
				return null;
			}
		}
		return result;
	}
}
2.3.11 beanPostProcessors 方法

addBeanPostProcessor 方法在 beanPostProcessors 属性中拥有 beanPostProcessor 参数时将其移到列表尾部,否则直接将该属性添加到尾部,在 beanPostProcessor 参数为 InstantiationAwareBeanPostProcessor 对象时将 hasInstantiationAwareBeanPostProcessors 属性置为 true,在其为 DestructionAwareBeanPostProcessor 对象时则会将 hasDestructionAwareBeanPostProcessors 属性置为 true;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
		Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
		this.beanPostProcessors.remove(beanPostProcessor);
		if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
			this.hasInstantiationAwareBeanPostProcessors = true;
		}
		if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
			this.hasDestructionAwareBeanPostProcessors = true;
		}
		this.beanPostProcessors.add(beanPostProcessor);
	}
}

getBeanPostProcessorCount、getBeanPostProcessors、hasInstantiationAwareBeanPostProcessors 及 hasDestructionAwareBeanPostProcessors 方法分别返回 beanPostProcessors 属性元素数量、该属性值、hasInstantiationAwareBeanPostProcessors 属性及 hasDestructionAwareBeanPostProcessors 属性值;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public int getBeanPostProcessorCount() {
		return this.beanPostProcessors.size();
	}

	public List<BeanPostProcessor> getBeanPostProcessors() {
		return this.beanPostProcessors;
	}

	protected boolean hasInstantiationAwareBeanPostProcessors() {
		return this.hasInstantiationAwareBeanPostProcessors;
	}

	protected boolean hasDestructionAwareBeanPostProcessors() {
		return this.hasDestructionAwareBeanPostProcessors;
	}
}
2.3.12 scopes 方法

registerScope 方法首先对 scopeName 与 scope 参数进行非空验证,随后验证 scopeName 是否不为 SCOPE_SINGLETON 与 SCOPE_PROTOTYPE 常量值,在通过后将 scopeName 与 scope 参数映射值保存到 scopes 属性中;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public void registerScope(String scopeName, Scope scope) {
		Assert.notNull(scopeName, "Scope identifier must not be null");
		Assert.notNull(scope, "Scope must not be null");
		if (SCOPE_SINGLETON.equals(scopeName) || SCOPE_PROTOTYPE.equals(scopeName)) {
			throw new IllegalArgumentException("Cannot replace existing scopes 'singleton' and 'prototype'");
		}
		Scope previous = this.scopes.put(scopeName, scope);
		if (previous != null && previous != scope) {
			if (logger.isDebugEnabled()) {
				logger.debug("Replacing scope '" + scopeName + "' from [" + previous + "] to [" + scope + "]");
			}
		}
		else {
			if (logger.isTraceEnabled()) {
				logger.trace("Registering scope '" + scopeName + "' with implementation [" + scope + "]");
			}
		}
	}
}

getRegisteredScopeNames 方法将 scopes 属性的 key 集合转化为字符串数组并返回;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public String[] getRegisteredScopeNames() {
		return StringUtils.toStringArray(this.scopes.keySet());
	}
}

getRegisteredScope 方法在通过对 scopeName 参数的非空验证后,从 scopes 属性中获取 scopeName 参数对应的 Scope 对象并返回;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	@Nullable
	public Scope getRegisteredScope(String scopeName) {
		Assert.notNull(scopeName, "Scope identifier must not be null");
		return this.scopes.get(scopeName);
	}
}
2.3.13 copyConfigurationFrom 方法

copyConfigurationFrom 方法首先对 otherFactory 参数进行非空验证,验证通过后将 otherFactory 参数的属性复制到当前对象工厂中;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
		Assert.notNull(otherFactory, "BeanFactory must not be null");
		setBeanClassLoader(otherFactory.getBeanClassLoader());
		setCacheBeanMetadata(otherFactory.isCacheBeanMetadata());
		setBeanExpressionResolver(otherFactory.getBeanExpressionResolver());
		setConversionService(otherFactory.getConversionService());
		if (otherFactory instanceof AbstractBeanFactory) {
			AbstractBeanFactory otherAbstractFactory = (AbstractBeanFactory) otherFactory;
			this.propertyEditorRegistrars.addAll(otherAbstractFactory.propertyEditorRegistrars);
			this.customEditors.putAll(otherAbstractFactory.customEditors);
			this.typeConverter = otherAbstractFactory.typeConverter;
			this.beanPostProcessors.addAll(otherAbstractFactory.beanPostProcessors);
			this.hasInstantiationAwareBeanPostProcessors = this.hasInstantiationAwareBeanPostProcessors ||
					otherAbstractFactory.hasInstantiationAwareBeanPostProcessors;
			this.hasDestructionAwareBeanPostProcessors = this.hasDestructionAwareBeanPostProcessors ||
					otherAbstractFactory.hasDestructionAwareBeanPostProcessors;
			this.scopes.putAll(otherAbstractFactory.scopes);
			this.securityContextProvider = otherAbstractFactory.securityContextProvider;
		}
		else {
			setTypeConverter(otherFactory.getTypeConverter());
			String[] otherScopeNames = otherFactory.getRegisteredScopeNames();
			for (String scopeName : otherScopeNames) {
				this.scopes.put(scopeName, otherFactory.getRegisteredScope(scopeName));
			}
		}
	}
}
2.3.14 copyConfigurationFrom 方法

getMergedBeanDefinition 方法在当前对象工厂不包含 name 参数对应对象注册表且父对象工厂为 ConfigurableBeanFactory 对象时直接执行父对象工厂的 getMergedBeanDefinition 方法获取对象注册表并返回;否则执行 getMergedLocalBeanDefinition 方法并返回。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public BeanDefinition getMergedBeanDefinition(String name) throws BeansException {
		String beanName = transformedBeanName(name);
		// Efficiently check whether bean definition exists in this factory.
		if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) {
			return ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(beanName);
		}
		// Resolve merged bean definition locally.
		return getMergedLocalBeanDefinition(beanName);
	}
}
2.3.15 isFactoryBean 方法

isFactoryBean 方法在当前工厂中拥有 name 对应的单例对象时,直接返回其是否为 FactoryBean 工厂对象,否则在当前对象工厂中不存在 name 对应的对象注册表且父对象工厂为 ConfigurableBeanFactory 对象时,通过父工厂的 isFactoryBean 方法判断 name 对应对象是否为对象工厂,否则通过 isFactoryBean 方法判断对应对象注册表是否为工厂对象。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException {
		String beanName = transformedBeanName(name);
		Object beanInstance = getSingleton(beanName, false);
		if (beanInstance != null) {
			return (beanInstance instanceof FactoryBean);
		}
		// No singleton instance found -> check bean definition.
		if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) {
			// No bean definition found in this factory -> delegate to parent.
			return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name);
		}
		return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName));
	}
}
2.3.16 isActuallyInCreation 方法

isActuallyInCreation 方法判断当前是否正在创建 beanName 对应单例对象或原型模式对象,其中 isPrototypeCurrentlyInCreation 直接返回 prototypesCurrentlyInCreation 属性对应的值是否包含 beanName 参数值。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public boolean isActuallyInCreation(String beanName) {
		return (isSingletonCurrentlyInCreation(beanName) || isPrototypeCurrentlyInCreation(beanName));
	}

	protected boolean isPrototypeCurrentlyInCreation(String beanName) {
		Object curVal = this.prototypesCurrentlyInCreation.get();
		return (curVal != null &&
				(curVal.equals(beanName) || (curVal instanceof Set && ((Set<?>) curVal).contains(beanName))));
	}
}
2.3.17 destroyBean 方法

destroyBean 方法创建 DisposableBeanAdapter 对象并调用其 destroy 方法销毁对象。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public void destroyBean(String beanName, Object beanInstance) {
		destroyBean(beanName, beanInstance, getMergedLocalBeanDefinition(beanName));
	}

	protected void destroyBean(String beanName, Object bean, RootBeanDefinition mbd) {
		new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), getAccessControlContext()).destroy();
	}
}
2.3.18 destroyScopedBean 方法

destroyScopedBean 方法在 beanName 参数对应对象注册表为单例或原型模式则直接抛出异常,随后获取对象注册表关联的 Scope 作用域对象,在其为 null 时也会抛出异常,然后调用其 remove 方法移除 beanName 对应对象并调用 destroyBean 销毁移除对象。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Override
	public void destroyScopedBean(String beanName) {
		RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
		if (mbd.isSingleton() || mbd.isPrototype()) {
			throw new IllegalArgumentException(
					"Bean name '" + beanName + "' does not correspond to an object in a mutable scope");
		}
		String scopeName = mbd.getScope();
		Scope scope = this.scopes.get(scopeName);
		if (scope == null) {
			throw new IllegalStateException("No Scope SPI registered for scope name '" + scopeName + "'");
		}
		Object bean = scope.remove(beanName);
		if (bean != null) {
			destroyBean(beanName, bean, mbd);
		}
	}
}

3 类方法

3.1 transformedBeanName 方法

transformedBeanName 方法首先调用 BeanFactoryUtils 类的 transformedBeanName 方法将 name 参数转换为实际对象名同时使用该结果执行 canonicalName 方法获取原始对象名;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	protected String transformedBeanName(String name) {
		return canonicalName(BeanFactoryUtils.transformedBeanName(name));
	}
}

BeanFactoryUtils 类的 transformedBeanName 方法首先对 name 参数进行非空验证,验证通过后,移除 name 参数的所有 FACTORY_BEAN_PREFIX 工厂对象名前缀,并将其与 name 参数映射值保存到 transformedBeanNameCache 缓存中并返回处理后的对象名;

java 复制代码
public abstract class BeanFactoryUtils {
	public static String transformedBeanName(String name) {
		Assert.notNull(name, "'name' must not be null");
		if (!name.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
			return name;
		}
		return transformedBeanNameCache.computeIfAbsent(name, beanName -> {
			do {
				beanName = beanName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
			}
			while (beanName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX));
			return beanName;
		});
	}
}

3.2 originalBeanName 方法

originalBeanName 方法首先调用 transformedBeanName 方法将 beanName 转换为原始对象名,在 name 参数为工厂对象名时,也会为获取到的原始对象名加上工厂对象名前缀并返回;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	protected String originalBeanName(String name) {
		String beanName = transformedBeanName(name);
		if (name.startsWith(FACTORY_BEAN_PREFIX)) {
			beanName = FACTORY_BEAN_PREFIX + beanName;
		}
		return beanName;
	}
}

3.3 initBeanWrapper 方法

initBeanWrapper 方法在将 conversionService 属性保存到 bw 属性中,并调用 registerCustomEditors 方法将其注册到 propertyEditorRegistrars 属性中;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	protected void initBeanWrapper(BeanWrapper bw) {
		bw.setConversionService(getConversionService());
		registerCustomEditors(bw);
	}
}

3.4 registerCustomEditors 方法

registerCustomEditors 方法在 registry 参数为 PropertyEditorRegistrySupport 对象时将其转化为 PropertyEditorRegistrySupport 对象并保存到 registrySupport 变量中,否则将该变量置为 null;随后在 registrySupport 变量不为 null 时首先调用 useConfigValueEditors 方法激活仅用于配置目的的配置值编辑器;并在 propertyEditorRegistrars 属性不为空时,将 registrySupport 变量逐一注册到该属性的元素中;随后在 customEditors 属性不为空时,将其所有元素全部注册到 registry 参数中;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	protected void registerCustomEditors(PropertyEditorRegistry registry) {
		PropertyEditorRegistrySupport registrySupport =
				(registry instanceof PropertyEditorRegistrySupport ? (PropertyEditorRegistrySupport) registry : null);
		if (registrySupport != null) {
			registrySupport.useConfigValueEditors();
		}
		if (!this.propertyEditorRegistrars.isEmpty()) {
			for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) {
				try {
					registrar.registerCustomEditors(registry);
				}
				catch (BeanCreationException ex) {
					Throwable rootCause = ex.getMostSpecificCause();
					if (rootCause instanceof BeanCurrentlyInCreationException) {
						BeanCreationException bce = (BeanCreationException) rootCause;
						String bceBeanName = bce.getBeanName();
						if (bceBeanName != null && isCurrentlyInCreation(bceBeanName)) {
							if (logger.isDebugEnabled()) {
								logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() +
										"] failed because it tried to obtain currently created bean '" +
										ex.getBeanName() + "': " + ex.getMessage());
							}
							onSuppressedException(ex);
							continue;
						}
					}
					throw ex;
				}
			}
		}
		if (!this.customEditors.isEmpty()) {
			this.customEditors.forEach((requiredType, editorClass) ->
					registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass)));
		}
	}
}

3.5 getMergedLocalBeanDefinition 方法

getMergedLocalBeanDefinition 方法在 beanName 对应的对象元数据不为 null 且其不需要重合并时直接返回 mergedBeanDefinitions 属性中对应的对象注册表;否则使用 getBeanDefinition 方法获取对应的注册表并通过 getMergedBeanDefinition 将其合并并保存到 mergedBeanDefinitions 属性中;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
		// Quick check on the concurrent map first, with minimal locking.
		RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
		if (mbd != null && !mbd.stale) {
			return mbd;
		}
		return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
	}

	protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;
}

3.6 getMergedBeanDefinition 方法

getMergedBeanDefinition 方法在 containingBd 参数为 null 时会尝试从 mergedBeanDefinitions 属性中获取 beanName 对应的 RootBeanDefinition 对象,在该对象不为 null 且不需要重新合并时直接返回该对象;否则会将 mbd 变量值保存到 previous 变量中,在 bd 参数没有父对象时且其为 RootBeanDefinition 对象时,将 mbd 变量更新为其的克隆值,在 bd 参数没有父对象时且其不为 RootBeanDefinition 对象时,则会将 mbd 变量更新为使用 bd 参数创建的 RootBeanDefinition 对象;在 bd 参数拥有父对象时,若其父对象名与 beanName 参数不同时,则会使用其父对象名执行 getMergedBeanDefinition 方法获取其父对象注册表并为 pbd 变量赋值,否则通过 getParentBeanFactory 方法获取父对象工厂,在其为 ConfigurableBeanFactory 对象时,则会从父对象工厂中获取父对象元数据对象并为 pbd 变量赋值,在其不为 ConfigurableBeanFactory 对象时,直接抛出异常,最后使用 pbd 变量创建 RootBeanDefinition 对象并使用 bd 参数对其进行重写然后为 mbd 属性赋值;之后进一步为 mbd 变量更新作用域,其中在其作用域为空时直接将其作用域设置为单例,在 containingBd 不为 null 且该参数不为单例但 mbd 变量是单例时将 mbd 变量的作用域更新为 containingBd 的作用域,最后在 containingBd 参数为 null 且需要对元数据进行缓存时将其保存到 mergedBeanDefinitions 缓存中; 最后在 previous 变量不为 null 时,需要时将 mbd 对应属性更新为其对应属性值并返回 mbd 变量值。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)
			throws BeanDefinitionStoreException {

		return getMergedBeanDefinition(beanName, bd, null);
	}

	protected RootBeanDefinition getMergedBeanDefinition(
			String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd)
			throws BeanDefinitionStoreException {

		synchronized (this.mergedBeanDefinitions) {
			RootBeanDefinition mbd = null;
			RootBeanDefinition previous = null;

			// Check with full lock now in order to enforce the same merged instance.
			if (containingBd == null) {
				mbd = this.mergedBeanDefinitions.get(beanName);
			}

			if (mbd == null || mbd.stale) {
				previous = mbd;
				if (bd.getParentName() == null) {
					// Use copy of given root bean definition.
					if (bd instanceof RootBeanDefinition) {
						mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
					}
					else {
						mbd = new RootBeanDefinition(bd);
					}
				}
				else {
					// Child bean definition: needs to be merged with parent.
					BeanDefinition pbd;
					try {
						String parentBeanName = transformedBeanName(bd.getParentName());
						if (!beanName.equals(parentBeanName)) {
							pbd = getMergedBeanDefinition(parentBeanName);
						}
						else {
							BeanFactory parent = getParentBeanFactory();
							if (parent instanceof ConfigurableBeanFactory) {
								pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);
							}
							else {
								throw new NoSuchBeanDefinitionException(parentBeanName,
										"Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
										"': cannot be resolved without a ConfigurableBeanFactory parent");
							}
						}
					}
					catch (NoSuchBeanDefinitionException ex) {
						throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
								"Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
					}
					// Deep copy with overridden values.
					mbd = new RootBeanDefinition(pbd);
					mbd.overrideFrom(bd);
				}

				// Set default singleton scope, if not configured before.
				if (!StringUtils.hasLength(mbd.getScope())) {
					mbd.setScope(SCOPE_SINGLETON);
				}

				// A bean contained in a non-singleton bean cannot be a singleton itself.
				// Let's correct this on the fly here, since this might be the result of
				// parent-child merging for the outer bean, in which case the original inner bean
				// definition will not have inherited the merged outer bean's singleton status.
				if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
					mbd.setScope(containingBd.getScope());
				}

				// Cache the merged bean definition for the time being
				// (it might still get re-merged later on in order to pick up metadata changes)
				if (containingBd == null && isCacheBeanMetadata()) {
					this.mergedBeanDefinitions.put(beanName, mbd);
				}
			}
			if (previous != null) {
				copyRelevantMergedBeanDefinitionCaches(previous, mbd);
			}
			return mbd;
		}
	}
}

copyRelevantMergedBeanDefinitionCaches 方法在 mdb 参数与 previous 参数的 beanClass、factoryBeanName、factoryMethodName 及 targetType 四个属性都相同时,将 mbd 的 isFactoryBean、resolvedTargetType、factoryMethodReturnType 及 factoryMethodToIntrospect 更新为 previous 参数的对应属性值;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	private void copyRelevantMergedBeanDefinitionCaches(RootBeanDefinition previous, RootBeanDefinition mbd) {
		if (ObjectUtils.nullSafeEquals(mbd.getBeanClassName(), previous.getBeanClassName()) &&
				ObjectUtils.nullSafeEquals(mbd.getFactoryBeanName(), previous.getFactoryBeanName()) &&
				ObjectUtils.nullSafeEquals(mbd.getFactoryMethodName(), previous.getFactoryMethodName())) {
			ResolvableType targetType = mbd.targetType;
			ResolvableType previousTargetType = previous.targetType;
			if (targetType == null || targetType.equals(previousTargetType)) {
				mbd.targetType = previousTargetType;
				mbd.isFactoryBean = previous.isFactoryBean;
				mbd.resolvedTargetType = previous.resolvedTargetType;
				mbd.factoryMethodReturnType = previous.factoryMethodReturnType;
				mbd.factoryMethodToIntrospect = previous.factoryMethodToIntrospect;
			}
		}
	}
}

3.7 checkMergedBeanDefinition 方法

checkMergedBeanDefinition 方法用于判断 mbd 是否为非抽象对象,若 mbd 参数的抽象标识置位则直接抛出异常;。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName, @Nullable Object[] args)
			throws BeanDefinitionStoreException {

		if (mbd.isAbstract()) {
			throw new BeanIsAbstractException(beanName);
		}
	}
}

3.8 clearMergedBeanDefinition 方法

clearMergedBeanDefinition 方法用于复位对象注册表,其将 beanName 对应对象注册表的 stale 属性标识为 true,表明需要重合并。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	protected void clearMergedBeanDefinition(String beanName) {
		RootBeanDefinition bd = this.mergedBeanDefinitions.get(beanName);
		if (bd != null) {
			bd.stale = true;
		}
	}
}

3.9 clearMetadataCache 方法

clearMetadataCache 方法将 mergedBeanDefinitions 属性中的已创建对象元素对应对象注册表的 stale 属性置为 true,表明再次使用时需要重合并。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	public void clearMetadataCache() {
		this.mergedBeanDefinitions.forEach((beanName, bd) -> {
			if (!isBeanEligibleForMetadataCaching(beanName)) {
				bd.stale = true;
			}
		});
	}

	protected boolean isBeanEligibleForMetadataCaching(String beanName) {
		return this.alreadyCreated.contains(beanName);
	}
}

3.10 resolveBeanClass 方法

resolveBeanClass 方法在 mbd 参数拥有 beanClass 属性时直接返回该属性值,否则使用 doResolveBeanClass 对 mbd 参数进行解析获取其中类对象。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Nullable
	protected Class<?> resolveBeanClass(RootBeanDefinition mbd, String beanName, Class<?>... typesToMatch)
			throws CannotLoadBeanClassException {

		try {
			if (mbd.hasBeanClass()) {
				return mbd.getBeanClass();
			}
			if (System.getSecurityManager() != null) {
				return AccessController.doPrivileged((PrivilegedExceptionAction<Class<?>>)
						() -> doResolveBeanClass(mbd, typesToMatch), getAccessControlContext());
			}
			else {
				return doResolveBeanClass(mbd, typesToMatch);
			}
		}
		catch (PrivilegedActionException pae) {
			ClassNotFoundException ex = (ClassNotFoundException) pae.getException();
			throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
		}
		catch (ClassNotFoundException ex) {
			throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
		}
		catch (LinkageError err) {
			throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), err);
		}
	}
}

doResolveBeanClass 方法在 typesToMatch 参数与 tempClassLoader 属性都不为空时,分别将 dynamicLoader 与 freshResolve 变量更新为 tempClassLoader 属性及 true,否则则分别将这两个变量更新为 beanClassLoader 属性与 false,进一步若 tempClassLoader 属性为 DecoratingClassLoader 对象时,从 tempClassLoader 中拍 typesToMatch 参数中的所有元素;之后在 mbd 参数关联类名为空时,直接使用 beanClassLoader 属性执行 mbd 参数的 resolveBeanClass 方法进行类加载和解析并返回,否则使用 evaluateBeanDefinitionString 方法对类名进行计算,若计算值不等于类名时,若其为 Class 对象直接返回该值,在其为字符串时,将 className 属性更新为计算值并将 freshResolve 置为 true,否则直接抛出异常;之后若 freshResolve 为 true,在 dynamicLoader 变量不为 null 时,直接使用其加载 className 对应类并返回,若 dynamicLoader 为 null 或上述类加载过程中出现了 ClassNotFoundException 异常则会调用 ClassUtils 类的 forName 对类进行加载;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Nullable
	private Class<?> doResolveBeanClass(RootBeanDefinition mbd, Class<?>... typesToMatch)
			throws ClassNotFoundException {

		ClassLoader beanClassLoader = getBeanClassLoader();
		ClassLoader dynamicLoader = beanClassLoader;
		boolean freshResolve = false;

		if (!ObjectUtils.isEmpty(typesToMatch)) {
			// When just doing type checks (i.e. not creating an actual instance yet),
			// use the specified temporary class loader (e.g. in a weaving scenario).
			ClassLoader tempClassLoader = getTempClassLoader();
			if (tempClassLoader != null) {
				dynamicLoader = tempClassLoader;
				freshResolve = true;
				if (tempClassLoader instanceof DecoratingClassLoader) {
					DecoratingClassLoader dcl = (DecoratingClassLoader) tempClassLoader;
					for (Class<?> typeToMatch : typesToMatch) {
						dcl.excludeClass(typeToMatch.getName());
					}
				}
			}
		}

		String className = mbd.getBeanClassName();
		if (className != null) {
			Object evaluated = evaluateBeanDefinitionString(className, mbd);
			if (!className.equals(evaluated)) {
				// A dynamically resolved expression, supported as of 4.2...
				if (evaluated instanceof Class) {
					return (Class<?>) evaluated;
				}
				else if (evaluated instanceof String) {
					className = (String) evaluated;
					freshResolve = true;
				}
				else {
					throw new IllegalStateException("Invalid class name expression result: " + evaluated);
				}
			}
			if (freshResolve) {
				// When resolving against a temporary class loader, exit early in order
				// to avoid storing the resolved Class in the bean definition.
				if (dynamicLoader != null) {
					try {
						return dynamicLoader.loadClass(className);
					}
					catch (ClassNotFoundException ex) {
						if (logger.isTraceEnabled()) {
							logger.trace("Could not load class [" + className + "] from " + dynamicLoader + ": " + ex);
						}
					}
				}
				return ClassUtils.forName(className, dynamicLoader);
			}
		}

		// Resolve regularly, caching the result in the BeanDefinition...
		return mbd.resolveBeanClass(beanClassLoader);
	}
}

3.11 evaluateBeanDefinitionString 方法

evaluateBeanDefinitionString 方法在 beanExpressionResolver 属性为 null 时直接返回 value 参数值,在 beanDefinition 对象注册表参数不为 null 时,将 scope 局部变量值更新为注册表的作用域对象,否则将 scope 变量置为 null,最后执行 beanExpressionResolver 属性的 evaluate 方法对 value 值进行计算并返回其计算结果。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Nullable
	protected Object evaluateBeanDefinitionString(@Nullable String value, @Nullable BeanDefinition beanDefinition) {
		if (this.beanExpressionResolver == null) {
			return value;
		}

		Scope scope = null;
		if (beanDefinition != null) {
			String scopeName = beanDefinition.getScope();
			if (scopeName != null) {
				scope = getRegisteredScope(scopeName);
			}
		}
		return this.beanExpressionResolver.evaluate(value, new BeanExpressionContext(this, scope));
	}
}

3.12 predictBeanType 方法

predictBeanType 方法首先获取 mbd 参数的目标类型,在其不为空时直接返回;否则若 mbd 参数的 factoryMethodName 属性不为空时直接返回 null;最后则会调用 resolveBeanClass 对 mbd 的类型进行解析并返回。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	@Nullable
	protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
		Class<?> targetType = mbd.getTargetType();
		if (targetType != null) {
			return targetType;
		}
		if (mbd.getFactoryMethodName() != null) {
			return null;
		}
		return resolveBeanClass(mbd, beanName, typesToMatch);
	}
}

3.13 isFactoryBean 方法

isFactoryBean 方法在 mbd 参数的 isFactoryBean 属性不为 null 时直接返回该属性值,在其为空时,则会调用 predictBeanType 方法对 mbd 的类型进行一个预测,若预测结果不为空且为 FactoryBean 对象时直接将 result 变量值更新为 true,最后在将 mbd 的 isFactoryBean 属性值更新为 result 变量值的同时返回该值;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	protected boolean isFactoryBean(String beanName, RootBeanDefinition mbd) {
		Boolean result = mbd.isFactoryBean;
		if (result == null) {
			Class<?> beanType = predictBeanType(beanName, mbd, FactoryBean.class);
			result = (beanType != null && FactoryBean.class.isAssignableFrom(beanType));
			mbd.isFactoryBean = result;
		}
		return result;
	}
}

3.14 getTypeForFactoryBean 方法

getTypeForFactoryBean 方法首先调用 getTypeForFactoryBeanFromAttributes 通过其属性获取其 ResolvableType 类型对象值,在其不为 NONE 时直接返回该值;否则在 allowInit 且 mbd 参数为单例对象时,通过 doGetBean 方法获取 beanName 对应的对象工厂,并获取其关联类型,若不为 null 直接返回该类型值,其余情况直接返回 NONE;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	protected ResolvableType getTypeForFactoryBean(String beanName, RootBeanDefinition mbd, boolean allowInit) {
		ResolvableType result = getTypeForFactoryBeanFromAttributes(mbd);
		if (result != ResolvableType.NONE) {
			return result;
		}

		if (allowInit && mbd.isSingleton()) {
			try {
				FactoryBean<?> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true);
				Class<?> objectType = getTypeForFactoryBean(factoryBean);
				return (objectType != null ? ResolvableType.forClass(objectType) : ResolvableType.NONE);
			}
			catch (BeanCreationException ex) {
				if (ex.contains(BeanCurrentlyInCreationException.class)) {
					logger.trace(LogMessage.format("Bean currently in creation on FactoryBean type check: %s", ex));
				}
				else if (mbd.isLazyInit()) {
					logger.trace(LogMessage.format("Bean creation exception on lazy FactoryBean type check: %s", ex));
				}
				else {
					logger.debug(LogMessage.format("Bean creation exception on eager FactoryBean type check: %s", ex));
				}
				onSuppressedException(ex);
			}
		}
		return ResolvableType.NONE;
	}
}

3.15 getTypeForFactoryBeanFromAttributes 方法

getTypeForFactoryBeanFromAttributes 方法首先获取 factoryBeanObjectType 属性值,在其不为 ResolvableType 或 Class 对象时直接返回空 ResolvableType 对象,否则将该属性值转化为 ResolvableType 对象并返回;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	ResolvableType getTypeForFactoryBeanFromAttributes(AttributeAccessor attributes) {
		Object attribute = attributes.getAttribute(FactoryBean.OBJECT_TYPE_ATTRIBUTE);
		if (attribute instanceof ResolvableType) {
			return (ResolvableType) attribute;
		}
		if (attribute instanceof Class) {
			return ResolvableType.forClass((Class<?>) attribute);
		}
		return ResolvableType.NONE;
	}
}

3.16 markBeanAsCreated 方法

markBeanAsCreated 方法将指定 beanName 标识为已创建,其在调用 clearMergedBeanDefinition 方法重置对象注册表的同时将 beanName 参数保存到 alreadyCreated 属性中以标识该对象已经创建。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	protected void markBeanAsCreated(String beanName) {
		if (!this.alreadyCreated.contains(beanName)) {
			synchronized (this.mergedBeanDefinitions) {
				if (!this.alreadyCreated.contains(beanName)) {
					clearMergedBeanDefinition(beanName);
					this.alreadyCreated.add(beanName);
				}
			}
		}
	}
}

3.17 cleanupAfterBeanCreationFailure 方法

cleanupAfterBeanCreationFailure 方法直接清空 alreadyCreated 属性。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	protected void cleanupAfterBeanCreationFailure(String beanName) {
		synchronized (this.mergedBeanDefinitions) {
			this.alreadyCreated.remove(beanName);
		}
	}
}

3.18 isBeanEligibleForMetadataCaching 方法

isBeanEligibleForMetadataCaching 方法直接返回 alreadyCreated 属性中是否包含 beanName 参数值。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	protected boolean isBeanEligibleForMetadataCaching(String beanName) {
		return this.alreadyCreated.contains(beanName);
	}
}

3.19 removeSingletonIfCreatedForTypeCheckOnly 方法

removeSingletonIfCreatedForTypeCheckOnly 方法在 alreadyCreated 属性中是否包含 beanName 参数值,表明对应对象只用于类型验证而未做其他使用时,移除对应单例对象并返回 true,否则返回 false。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	protected boolean removeSingletonIfCreatedForTypeCheckOnly(String beanName) {
		if (!this.alreadyCreated.contains(beanName)) {
			removeSingleton(beanName);
			return true;
		}
		else {
			return false;
		}
	}
}

3.20 hasBeanCreationStarted 方法

hasBeanCreationStarted 方法返回 alreadyCreated 属性是否不为空,用于判断是否已经开始创建对象。

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	protected boolean hasBeanCreationStarted() {
		return !this.alreadyCreated.isEmpty();
	}
}

3.21 isBeanNameInUse 方法

isBeanNameInUse 方法直接返回当前对象工厂中是否拥有任何使用 beanName 参数的地方;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	public boolean isBeanNameInUse(String beanName) {
		return isAlias(beanName) || containsLocalBean(beanName) || hasDependentBean(beanName);
	}
}

3.22 requiresDestruction 方法

requiresDestruction 方法直接返回当前对象工厂中是否拥有任何使用 beanName 参数的地方;

java 复制代码
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) {
		return (bean.getClass() != NullBean.class &&
				(DisposableBeanAdapter.hasDestroyMethod(bean, mbd) || (hasDestructionAwareBeanPostProcessors() &&
						DisposableBeanAdapter.hasApplicableProcessors(bean, getBeanPostProcessors()))));
	}
}

AbstractAutowireCapableBeanFactory 类

AbstractAutowireCapableBeanFactory 类在继承了 AbstractBeanFactory 类并实现了 AutowireCapableBeanFactory 接口,其默认实现 bean 对象的创建,其提供了对象创建属性填充,联机及初始化相关功能;

1 属性及构造方法

1.1 类属性

instantiationStrategy 属性保存的是对象创建策略对象,其默认初始化为 CglibSubclassingInstantiationStrategy 对象;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();
}

parameterNameDiscoverer 属性保存的是方法参数名解析策略,默认初始化为 DefaultParameterNameDiscoverer 对象;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Nullable
	private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
}

allowCircularReferences 与 allowRawInjectionDespiteWrapping 属性分别标识的是是否允许循环依赖与循环依赖时是否需要注入生 bean 对象,分别为 true 与 false,表明默认允许循环依赖但循环依赖时不需要注入生对象;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	private boolean allowCircularReferences = true;

	private boolean allowRawInjectionDespiteWrapping = false;
}

ignoredDependencyTypes 与 ignoredDependencyInterfaces 属性分别保存的是在依赖检查与自动注入过程中需要忽略的类型与接口集合;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	private final Set<Class<?>> ignoredDependencyTypes = new HashSet<>();

	private final Set<Class<?>> ignoredDependencyInterfaces = new HashSet<>();
}

currentlyCreatedBean 属性为线程与当前正在创建对象名的映射;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	private final NamedThreadLocal<String> currentlyCreatedBean = new NamedThreadLocal<>("Currently created bean");
}

factoryBeanInstanceCache、factoryMethodCandidateCache 与 filteredPropertyDescriptorsCache 属性分别为工厂对象、对象工厂方法及已筛选PropertyDescriptors 缓存;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	private final ConcurrentMap<String, BeanWrapper> factoryBeanInstanceCache = new ConcurrentHashMap<>();

	private final ConcurrentMap<Class<?>, Method[]> factoryMethodCandidateCache = new ConcurrentHashMap<>();

	private final ConcurrentMap<Class<?>, PropertyDescriptor[]> filteredPropertyDescriptorsCache =
			new ConcurrentHashMap<>();
}

1.2 构造方法

无参构造方法在执行完父类的无参构造方法后,将 BeanNameAware、BeanFactoryAware 及 BeanClassLoaderAware 三个接口对象保存到 ignoreDependencyInterfaces 属性中来表明需要注入忽略这三类接口;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	public AbstractAutowireCapableBeanFactory() {
		super();
		ignoreDependencyInterface(BeanNameAware.class);
		ignoreDependencyInterface(BeanFactoryAware.class);
		ignoreDependencyInterface(BeanClassLoaderAware.class);
	}

	public void ignoreDependencyInterface(Class<?> ifc) {
		this.ignoredDependencyInterfaces.add(ifc);
	}
}

在拥有一个 parentBeanFactory 参数的构造方法在执行无参构造方法后,将 parentBeanFactory 参数设置为父对象工厂;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	public AbstractAutowireCapableBeanFactory(@Nullable BeanFactory parentBeanFactory) {
		this();
		setParentBeanFactory(parentBeanFactory);
	}
}

2 set 与 get 方法

AbstractAutowireCapableBeanFactory 类提供了 instantiationStrategy 与 parameterNameDiscoverer 属性的 set 与 get 方法,同时只提供了 allowRawInjectionDespiteWrapping 与allowCircularReferences 属性的 set 方法;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
		this.instantiationStrategy = instantiationStrategy;
	}

	protected InstantiationStrategy getInstantiationStrategy() {
		return this.instantiationStrategy;
	}

	public void setParameterNameDiscoverer(@Nullable ParameterNameDiscoverer parameterNameDiscoverer) {
		this.parameterNameDiscoverer = parameterNameDiscoverer;
	}

	@Nullable
	protected ParameterNameDiscoverer getParameterNameDiscoverer() {
		return this.parameterNameDiscoverer;
	}

	public void setAllowCircularReferences(boolean allowCircularReferences) {
		this.allowCircularReferences = allowCircularReferences;
	}

	public void setAllowRawInjectionDespiteWrapping(boolean allowRawInjectionDespiteWrapping) {
		this.allowRawInjectionDespiteWrapping = allowRawInjectionDespiteWrapping;
	}
}

3copyConfigurationFrom 方法

copyConfigurationFrom 方法在调用父类的 copyConfigurationFrom 方法将 otherFactory 参数的对应属性复制到当前对象中,并在其为 AbstractAutowireCapableBeanFactory 对象时,将其的 instantiationStrategy 与 allowCircularReferences 属性复制到当前属性中,同时将其的 ignoredDependencyTypes 与 ignoredDependencyInterfaces 属性值全量添加到本对象的对应属性中;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Override
	public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
		super.copyConfigurationFrom(otherFactory);
		if (otherFactory instanceof AbstractAutowireCapableBeanFactory) {
			AbstractAutowireCapableBeanFactory otherAutowireFactory =
					(AbstractAutowireCapableBeanFactory) otherFactory;
			this.instantiationStrategy = otherAutowireFactory.instantiationStrategy;
			this.allowCircularReferences = otherAutowireFactory.allowCircularReferences;
			this.ignoredDependencyTypes.addAll(otherAutowireFactory.ignoredDependencyTypes);
			this.ignoredDependencyInterfaces.addAll(otherAutowireFactory.ignoredDependencyInterfaces);
		}
	}
}

4 外部对象创建方法

4.1 createBean 方法

单参数 createBean 方法实现在使用 beanClass 参数创建 RootBeanDefinition 对象之后,分别将其作用域与 allowCaching 属性设置为原型模式与 beanClass 参数在当前类加载器中是否可缓存,最后使用类名、创建的注册表及 null 值执行三参数 createBean 创建对象并返回;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Override
	@SuppressWarnings("unchecked")
	public <T> T createBean(Class<T> beanClass) throws BeansException {
		// Use prototype bean definition, to avoid registering bean as dependent bean.
		RootBeanDefinition bd = new RootBeanDefinition(beanClass);
		bd.setScope(SCOPE_PROTOTYPE);
		bd.allowCaching = ClassUtils.isCacheSafe(beanClass, getBeanClassLoader());
		return (T) createBean(beanClass.getName(), bd, null);
	}
}

4.2 autowireBean 方法

autowireBean 方法首先通过 ClassUtils 类的 getUserClass 方法获取 existingBean 参数对应的用户类并使用该类型创建 RootBeanDefinition 对象,同时将其作用域与 allowCaching 属性设置为原型模式及对应类型在当前类加载器中是否可缓存;随后使用 existingBean 创建 BeanWrapperImpl 对象并使用 initBeanWrapper 属性对创建的 existingBean 参数封装对象进行初始化,最后调用 populateBean 方法为封装对象填充属性值。

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Override
	public void autowireBean(Object existingBean) {
		// Use non-singleton bean definition, to avoid registering bean as dependent bean.
		RootBeanDefinition bd = new RootBeanDefinition(ClassUtils.getUserClass(existingBean));
		bd.setScope(SCOPE_PROTOTYPE);
		bd.allowCaching = ClassUtils.isCacheSafe(bd.getBeanClass(), getBeanClassLoader());
		BeanWrapper bw = new BeanWrapperImpl(existingBean);
		initBeanWrapper(bw);
		populateBean(bd.getBeanClass().getName(), bd, bw);
	}
}

4.3 configureBean 方法

configureBean 方法首先使用 markBeanAsCreated 方法将 beanName 属性标记为已创建,随后使用 getMergedBeanDefinition 方法获取 beanName 的注册表;在其为 RootBeanDefinition 对象时,将 bd 变量值更新为获取到的对象注册表值,值得注意的是,在其作用域为原型模式时,则是更新为克隆值而不是原对象;在其不为 RootBeanDefinition 对象时,将 bd 变量值更新为使用该对象创建的 RootBeanDefinition 值;随后若 bd 变量不为原型模式时,将其作用域与 allowCaching 属性设置为原型模式及对应类型在当前类加载器中是否可缓存;最后也是会使用 BeanWrapperImpl 对象来封装 existingBean 对象,同时调用 initBeanWrapper 与 populateBean 方法对其进行初始化同时进行属性填充,最后执行 initializeBean 方法对 existingBean 对象进行初始化(包含执行 init 方法及后处理方法)并返回。

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Override
	public Object configureBean(Object existingBean, String beanName) throws BeansException {
		markBeanAsCreated(beanName);
		BeanDefinition mbd = getMergedBeanDefinition(beanName);
		RootBeanDefinition bd = null;
		if (mbd instanceof RootBeanDefinition) {
			RootBeanDefinition rbd = (RootBeanDefinition) mbd;
			bd = (rbd.isPrototype() ? rbd : rbd.cloneBeanDefinition());
		}
		if (bd == null) {
			bd = new RootBeanDefinition(mbd);
		}
		if (!bd.isPrototype()) {
			bd.setScope(SCOPE_PROTOTYPE);
			bd.allowCaching = ClassUtils.isCacheSafe(ClassUtils.getUserClass(existingBean), getBeanClassLoader());
		}
		BeanWrapper bw = new BeanWrapperImpl(existingBean);
		initBeanWrapper(bw);
		populateBean(beanName, bd, bw);
		return initializeBean(beanName, existingBean, bd);
	}
}

5 对象生命周期控制方法

5.1 createBean 方法

createBean 方法首先使用 beanClass、autowireMode 及 dependencyCheck 参数创建 RootBeanDefinition 注册表对象并将其作用域设置为原型,最后使用类名与创建的对象注册表调用三参数 createBean 方法创建对象并返回;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Override
	public Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException {
		// Use non-singleton bean definition, to avoid registering bean as dependent bean.
		RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck);
		bd.setScope(SCOPE_PROTOTYPE);
		return createBean(beanClass.getName(), bd, null);
	}
}

5.2 autowire 方法

autowire 方法首先也是使用 beanClass、autowireMode 及 dependencyCheck 参数创建 RootBeanDefinition 注册表对象并将其作用域设置为原型;之后在注册表对象为通过构造方法自动注入时执行 autowireConstructor 方法并返回;否则最后使用类名与创建的对象注册表调用三参数 createBean 方法创建对象并返回;否则使用 instantiationStrategy 属性的 instantiate 方法创建默认 bd 参数对应空对象,并执行 populateBean 方法为其设置属性值;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Override
	public Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException {
		// Use non-singleton bean definition, to avoid registering bean as dependent bean.
		RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck);
		bd.setScope(SCOPE_PROTOTYPE);
		if (bd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR) {
			return autowireConstructor(beanClass.getName(), bd, null, null).getWrappedInstance();
		}
		else {
			Object bean;
			if (System.getSecurityManager() != null) {
				bean = AccessController.doPrivileged(
						(PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(bd, null, this),
						getAccessControlContext());
			}
			else {
				bean = getInstantiationStrategy().instantiate(bd, null, this);
			}
			populateBean(beanClass.getName(), bd, new BeanWrapperImpl(bean));
			return bean;
		}
	}
}

5.3 autowireBeanProperties 方法

autowireBeanProperties 方法在 autowireMode 为 AUTOWIRE_CONSTRUCTOR 时直接抛出 IllegalArgumentException 异常;否则使用 existingBean 参数对应类型、autowireMode 及 dependencyCheck 参数创建 RootBeanDefinition 注册表对象并将其作用域设置为原型,同时使用 BeanWrapperImpl 对 existingBean 参数进行封装并使用 initBeanWrapper 方法对其进行初始化;最后调用 populateBean 方法为 existingBean 参数注入属性值。

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Override
	public void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck)
			throws BeansException {

		if (autowireMode == AUTOWIRE_CONSTRUCTOR) {
			throw new IllegalArgumentException("AUTOWIRE_CONSTRUCTOR not supported for existing bean instance");
		}
		// Use non-singleton bean definition, to avoid registering bean as dependent bean.
		RootBeanDefinition bd =
				new RootBeanDefinition(ClassUtils.getUserClass(existingBean), autowireMode, dependencyCheck);
		bd.setScope(SCOPE_PROTOTYPE);
		BeanWrapper bw = new BeanWrapperImpl(existingBean);
		initBeanWrapper(bw);
		populateBean(bd.getBeanClass().getName(), bd, bw);
	}
}

5.4 applyBeanPropertyValues 方法

applyBeanPropertyValues 方法首先将 beanName 标识为正在创建,随后获取其对应的注册表对象,并使用 BeanWrapperImpl 对 existingBean 参数进行封装同时使用 initBeanWrapper 方法对其进行初始化;最后调用多参数为对象工厂中其他对象属性进行赋值。

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Override
	public void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException {
		markBeanAsCreated(beanName);
		BeanDefinition bd = getMergedBeanDefinition(beanName);
		BeanWrapper bw = new BeanWrapperImpl(existingBean);
		initBeanWrapper(bw);
		applyPropertyValues(beanName, bd, bw, bd.getPropertyValues());
	}
}

5.5 initializeBean 方法

initializeBean 方法直接调用三参数构造方法对 existingBean 参数进行初始化并返回。

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Override
	public Object initializeBean(Object existingBean, String beanName) {
		return initializeBean(beanName, existingBean, null);
	}
}

5.6 applyBeanPostProcessorsBeforeInitialization 方法

applyBeanPostProcessorsBeforeInitialization 方法依次递归执行 beanPostProcessors 属性中所有后处理器的 postProcessBeforeInitialization 方法,并在执行完毕后返回执行结果,值得注意的是,一旦出现了执行结果为 null 时,则会返回上一个后处理器的执行结果。

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Override
	public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
			throws BeansException {

		Object result = existingBean;
		for (BeanPostProcessor processor : getBeanPostProcessors()) {
			Object current = processor.postProcessBeforeInitialization(result, beanName);
			if (current == null) {
				return result;
			}
			result = current;
		}
		return result;
	}
}

5.7 applyBeanPostProcessorsAfterInitialization 方法

applyBeanPostProcessorsBeforeInitialization 方法依次递归执行 beanPostProcessors 属性中所有后处理器的 postProcessAfterInitialization 方法,并在执行完毕后返回执行结果,值得注意的是,与上一方法一样一旦出现了执行结果为 null 时,则会返回上一个后处理器的执行结果。

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Override
	public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
			throws BeansException {

		Object result = existingBean;
		for (BeanPostProcessor processor : getBeanPostProcessors()) {
			Object current = processor.postProcessAfterInitialization(result, beanName);
			if (current == null) {
				return result;
			}
			result = current;
		}
		return result;
	}
}

5.8 destroyBean 方法

destroyBean 方法使用 existingBean 参数、beanPostProcessors 属性及安全控制器属性创建 DisposableBeanAdapter 方法并执行其 destroy 方法销毁该对象。

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Override
	public void destroyBean(Object existingBean) {
		new DisposableBeanAdapter(existingBean, getBeanPostProcessors(), getAccessControlContext()).destroy();
	}
}

6 对象注入点位解析方法

6.1 resolveBeanByName方法

resolveBeanByName 方法在使用 ConstructorResolver 类的 setCurrentInjectionPoint 方法将 descriptor 参数保存到当前的注入点中,并尝试使用 name 参数与 descriptor 参数对应的依赖类型执行 getBean 方法并返回,最后将当前的注入点还原到之前状态;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Override
	public Object resolveBeanByName(String name, DependencyDescriptor descriptor) {
		InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
		try {
			return getBean(name, descriptor.getDependencyType());
		}
		finally {
			ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
		}
	}
}

6.2 resolveDependency方法

resolveDependency 方法直接执行 4 参数 resolveDependency 方法解析其依赖并返回;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Override
	@Nullable
	public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName) throws BeansException {
		return resolveDependency(descriptor, requestingBeanName, null, null);
	}
}

7 AbstractBeanFactory 抽象方法

7.1 createBean方法

createBean 方法首先调用 resolveBeanClass 方法解析 mdb 中 beanName 参数对应的对象类型并保存到 resolvedClass 变量中,若其不为 null、mbd 没有 beanClass 属性且 mbd 参数的对应对象类型名为空时,使用 mbd 参数创建 RootBeanDefinition 对象并将其关联类型设置为 resolvedClass 属性值同时保存到 mbdToUse 变量中,否则直接将 mbdToUse 变量值设置为 mbd 参数值;随后调用 mbdToUse 变量的 prepareMethodOverrides 方法对其重写方法进行准备,同时尝试使用 beanName 参数与 mbdToUse 变量执行 resolveBeforeInstantiation 方法获取未初始化的对象,并在其不为 null 时直接返回,否则调用 doCreateBean 方法创建对象并返回;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Override
	protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {

		if (logger.isTraceEnabled()) {
			logger.trace("Creating instance of bean '" + beanName + "'");
		}
		RootBeanDefinition mbdToUse = mbd;

		// Make sure bean class is actually resolved at this point, and
		// clone the bean definition in case of a dynamically resolved Class
		// which cannot be stored in the shared merged bean definition.
		Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
		if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
			mbdToUse = new RootBeanDefinition(mbd);
			mbdToUse.setBeanClass(resolvedClass);
		}

		// Prepare method overrides.
		try {
			mbdToUse.prepareMethodOverrides();
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
					beanName, "Validation of method overrides failed", ex);
		}

		try {
			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
			Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
			if (bean != null) {
				return bean;
			}
		}
		catch (Throwable ex) {
			throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
					"BeanPostProcessor before instantiation of bean failed", ex);
		}

		try {
			Object beanInstance = doCreateBean(beanName, mbdToUse, args);
			if (logger.isTraceEnabled()) {
				logger.trace("Finished creating instance of bean '" + beanName + "'");
			}
			return beanInstance;
		}
		catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
			// A previously detected exception with proper bean creation context already,
			// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
			throw ex;
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
		}
	}
}

doCreateBean 方法在 mbd 参数为单例对象时,尝试从 factoryBeanInstanceCache 缓存中获取对应单例对象保存到 instanceWrapper 变量中并移除出缓存,在其不为单例对象但当前还未保存到缓存中时,则会调用 createBeanInstance 方法创建 mbd 对应实例并保存到 instanceWrapper 变量中,随后在 instanceWrapper 变量的内部封装对象类型不为 NullBean 时将 mbd 参数的目标解析类型更新为该类型值,随后在 mbd 关联对象还未执行后处理逻辑使用调用 applyMergedBeanDefinitionPostProcessors 方法为其执行后处理逻辑并将 mbd 参数的 postProcessed 属性置为 true,表明其已执行后处理器;之后在 mbd 为单例、允许循环依赖且 beanName 对应对象正在创建中,调用 addSingletonFactory 方法将使用 getEarlyBeanReference 方法实现的对象工厂对象保存到单例对象工厂缓存中;随后使用 populateBean 方法设置对象属性值,并调用 initializeBean 方法对对象进行初始化,并将初始化结果保存到 exposedObject 变量中;随后若 mbd 为单例、允许循环依赖且 beanName 对应对象正在创建中时,使用 getSingleton 获取 beanName 对应单例对象,在获取到该单例对象且 exposedObject 变量值与 instanceWrapper 变量的封装对象一致时,将 exposedObject 变量值更新为获取到的单例对象值;在获取到了对象、 exposedObject 变量值与 instanceWrapper 变量的封装对象不一致、allowRawInjectionDespiteWrapping 属性值为 false 且 beanName 拥有依赖对象时,若其依赖对象中存在已完成创建的单例对象时抛出异常;最后调用 registerDisposableBeanIfNecessary 方法尝试将 bean 注册为 DisposableBean 对象并返回 exposedObject 变量值;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {

		// Instantiate the bean.
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		Object bean = instanceWrapper.getWrappedInstance();
		Class<?> beanType = instanceWrapper.getWrappedClass();
		if (beanType != NullBean.class) {
			mbd.resolvedTargetType = beanType;
		}

		// Allow post-processors to modify the merged bean definition.
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				}
				catch (Throwable ex) {
					throw new BeanCreationException(mbd.getResourceDescription(), beanName,
							"Post-processing of merged bean definition failed", ex);
				}
				mbd.postProcessed = true;
			}
		}

		// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isTraceEnabled()) {
				logger.trace("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}

		// Initialize the bean instance.
		Object exposedObject = bean;
		try {
			populateBean(beanName, mbd, instanceWrapper);
			exposedObject = initializeBean(beanName, exposedObject, mbd);
		}
		catch (Throwable ex) {
			if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
				throw (BeanCreationException) ex;
			}
			else {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
			}
		}

		if (earlySingletonExposure) {
			Object earlySingletonReference = getSingleton(beanName, false);
			if (earlySingletonReference != null) {
				if (exposedObject == bean) {
					exposedObject = earlySingletonReference;
				}
				else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
					String[] dependentBeans = getDependentBeans(beanName);
					Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
					for (String dependentBean : dependentBeans) {
						if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
							actualDependentBeans.add(dependentBean);
						}
					}
					if (!actualDependentBeans.isEmpty()) {
						throw new BeanCurrentlyInCreationException(beanName,
								"Bean with name '" + beanName + "' has been injected into other beans [" +
								StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
								"] in its raw version as part of a circular reference, but has eventually been " +
								"wrapped. This means that said other beans do not use the final version of the " +
								"bean. This is often the result of over-eager type matching - consider using " +
								"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
					}
				}
			}
		}

		// Register bean as disposable.
		try {
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

		return exposedObject;
	}
}

applyMergedBeanDefinitionPostProcessors 方法使用 beanPostProcessors 属性中所有 MergedBeanDefinitionPostProcessor 类型后处理器的 postProcessMergedBeanDefinition 方法对 mbd 参数进行处理;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			if (bp instanceof MergedBeanDefinitionPostProcessor) {
				MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
				bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
			}
		}
	}
}

getEarlyBeanReference 方法用于获取指定对象的早期引用以用于解决循环依赖问题;其在 mbd 参数为合成对象注册表且拥有 InstantiationAwareBeanPostProcessor 后处理器时,将会对 bean 参数执行其中的 SmartInstantiationAwareBeanPostProcessor 类型后处理器的 getEarlyBeanReference 方法并在执行完毕后返回处理后的值;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
		Object exposedObject = bean;
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
					SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
					exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
				}
			}
		}
		return exposedObject;
	}
}

7.2 predictBeanType方法

predictBeanType 方法;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Override
	@Nullable
	protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
		Class<?> targetType = determineTargetType(beanName, mbd, typesToMatch);
		// Apply SmartInstantiationAwareBeanPostProcessors to predict the
		// eventual type after a before-instantiation shortcut.
		if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			boolean matchingOnlyFactoryBean = typesToMatch.length == 1 && typesToMatch[0] == FactoryBean.class;
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
					SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
					Class<?> predicted = ibp.predictBeanType(targetType, beanName);
					if (predicted != null &&
							(!matchingOnlyFactoryBean || FactoryBean.class.isAssignableFrom(predicted))) {
						return predicted;
					}
				}
			}
		}
		return targetType;
	}
}

7.3 determineTargetType方法

determineTargetType 方法用于确定指定 mbd 注册表的类型;在 mbd 注册表的目标类型不为空时直接返回该值,否则在 mbd 参数关联了对象工厂方法时,使用 getTypeForFactoryMethod 方法解析其工厂方法对应类型构造调用 resolveBeanClass 方法解析其类型,随后在 typesToMatch 参数为 null 或临时类加载器为空时将 mbd 的 resolvedTargetType 属性更新为解析的类型,最后返回解析类型;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Nullable
	protected Class<?> determineTargetType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
		Class<?> targetType = mbd.getTargetType();
		if (targetType == null) {
			targetType = (mbd.getFactoryMethodName() != null ?
					getTypeForFactoryMethod(beanName, mbd, typesToMatch) :
					resolveBeanClass(mbd, beanName, typesToMatch));
			if (ObjectUtils.isEmpty(typesToMatch) || getTempClassLoader() == null) {
				mbd.resolvedTargetType = targetType;
			}
		}
		return targetType;
	}
}

getTypeForFactoryMethod 方法通过对象工厂方法确定指定类型;在 mbd 参数的 factoryMethodReturnType 属性不为空,直接解析该属性来确定目标类型并返回;

同时在该参数的 factoryMethodToIntrospect 方法为 null 时,首先通过 mbd 注册表的 getFactoryBeanName 方法尝试获取其 factoryBeanName 工厂对象名属性,若其不为 null 但其值与 beanName 参数相同时直接抛出异常,不等于 beanName 时调用 getType 方法获取该 factoryBeanName 对应类型并保存到 factoryClass 局部变量中,并将 isStatic 变量更新为 false;在其没有对应的工厂对象名时,则会将 factoryClass 局部变量值更新为 resolveBeanClass 方法执行结果并将 isStatic 变量更新为 true;若通过上述两种方式都未能为 factoryClass 赋上值直接返回 null;否则将 factoryClass 变量更新为实际用户声明类型;

随后寻找 factoryClass 局部变量中的对应对象工厂方法,同时将 uniqueCandidate 与 commonType 参数更新为对象工厂方法对象与方法返回值,若为 null 时直接返回 null;随后将 mbd 参数的 factoryMethodToIntrospect 属性更新为 uniqueCandidate 变量值;最后将 mbd 参数的 factoryMethodReturnType 属性值更新为对象工厂方法的返回类型,并返回其解析结果;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Nullable
	protected Class<?> getTypeForFactoryMethod(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
		ResolvableType cachedReturnType = mbd.factoryMethodReturnType;
		if (cachedReturnType != null) {
			return cachedReturnType.resolve();
		}

		Class<?> commonType = null;
		Method uniqueCandidate = mbd.factoryMethodToIntrospect;

		if (uniqueCandidate == null) {
			Class<?> factoryClass;
			boolean isStatic = true;

			String factoryBeanName = mbd.getFactoryBeanName();
			if (factoryBeanName != null) {
				if (factoryBeanName.equals(beanName)) {
					throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
							"factory-bean reference points back to the same bean definition");
				}
				// Check declared factory method return type on factory class.
				factoryClass = getType(factoryBeanName);
				isStatic = false;
			}
			else {
				// Check declared factory method return type on bean class.
				factoryClass = resolveBeanClass(mbd, beanName, typesToMatch);
			}

			if (factoryClass == null) {
				return null;
			}
			factoryClass = ClassUtils.getUserClass(factoryClass);

			// If all factory methods have the same return type, return that type.
			// Can't clearly figure out exact method due to type converting / autowiring!
			int minNrOfArgs =
					(mbd.hasConstructorArgumentValues() ? mbd.getConstructorArgumentValues().getArgumentCount() : 0);
			Method[] candidates = this.factoryMethodCandidateCache.computeIfAbsent(factoryClass,
					clazz -> ReflectionUtils.getUniqueDeclaredMethods(clazz, ReflectionUtils.USER_DECLARED_METHODS));

			for (Method candidate : candidates) {
				if (Modifier.isStatic(candidate.getModifiers()) == isStatic && mbd.isFactoryMethod(candidate) &&
						candidate.getParameterCount() >= minNrOfArgs) {
					// Declared type variables to inspect?
					if (candidate.getTypeParameters().length > 0) {
						try {
							// Fully resolve parameter names and argument values.
							Class<?>[] paramTypes = candidate.getParameterTypes();
							String[] paramNames = null;
							ParameterNameDiscoverer pnd = getParameterNameDiscoverer();
							if (pnd != null) {
								paramNames = pnd.getParameterNames(candidate);
							}
							ConstructorArgumentValues cav = mbd.getConstructorArgumentValues();
							Set<ConstructorArgumentValues.ValueHolder> usedValueHolders = new HashSet<>(paramTypes.length);
							Object[] args = new Object[paramTypes.length];
							for (int i = 0; i < args.length; i++) {
								ConstructorArgumentValues.ValueHolder valueHolder = cav.getArgumentValue(
										i, paramTypes[i], (paramNames != null ? paramNames[i] : null), usedValueHolders);
								if (valueHolder == null) {
									valueHolder = cav.getGenericArgumentValue(null, null, usedValueHolders);
								}
								if (valueHolder != null) {
									args[i] = valueHolder.getValue();
									usedValueHolders.add(valueHolder);
								}
							}
							Class<?> returnType = AutowireUtils.resolveReturnTypeForFactoryMethod(
									candidate, args, getBeanClassLoader());
							uniqueCandidate = (commonType == null && returnType == candidate.getReturnType() ?
									candidate : null);
							commonType = ClassUtils.determineCommonAncestor(returnType, commonType);
							if (commonType == null) {
								// Ambiguous return types found: return null to indicate "not determinable".
								return null;
							}
						}
						catch (Throwable ex) {
							if (logger.isDebugEnabled()) {
								logger.debug("Failed to resolve generic return type for factory method: " + ex);
							}
						}
					}
					else {
						uniqueCandidate = (commonType == null ? candidate : null);
						commonType = ClassUtils.determineCommonAncestor(candidate.getReturnType(), commonType);
						if (commonType == null) {
							// Ambiguous return types found: return null to indicate "not determinable".
							return null;
						}
					}
				}
			}

			mbd.factoryMethodToIntrospect = uniqueCandidate;
			if (commonType == null) {
				return null;
			}
		}

		// Common return type found: all factory methods return same type. For a non-parameterized
		// unique candidate, cache the full type declaration context of the target factory method.
		cachedReturnType = (uniqueCandidate != null ?
				ResolvableType.forMethodReturnType(uniqueCandidate) : ResolvableType.forClass(commonType));
		mbd.factoryMethodReturnType = cachedReturnType;
		return cachedReturnType.resolve();
	}
}

7.4 getTypeForFactoryBean方法

getTypeForFactoryBean 方法用于确定 mbd 对应对象工厂的对应属性类型;其首先尝试通过 getTypeForFactoryBeanFromAttributes 方法获取 mbd 注册表参数中设置的类型,若其值不为 ResolvableType 的 NONE 常量值时,直接返回该属性值;在 mbd 拥有 beanClass 属性时使用该属性值创建 ResolvableType 对象为 beanType 变量赋值,否则将该变量值初始化为 NONE 常量值;在 mbd 参数拥有对象创建回调函数时,尝试将其目标类型或 beanType 变量值转化为 FactoryBean 对象并获取其泛型类型并保存到 result 变量中,若获取到对应值时直接返回;

随后若 mbd 参数关联 factoryBeanName 工厂对象名与 factoryMethodName 工厂方法名都不为 null 时,若 factoryBeanName 参数对应注册表为 AbstractBeanDefinition 对象且已经设置了对象类型时,将 factoryBeanClass 变量值更新为该对象工厂类型,否则通过 getMergedBeanDefinition 与 getMergedBeanDefinition 方法获取对应对象工厂类型并保存到 factoryBeanClass 变量中;随后若该变量不为空,则尝试通过 getTypeForFactoryBeanFromMethod 方法获取对应类型值在获取到时直接返回该结果解析类型;之后若还未创建 factoryBeanName 工厂对象时直接返回 ResolvableType 类的 NONE 常量值;

随后若 allowInit 参数为 true ,即允许先对对象工厂进行初始化在通过其 getObjectType 方法获取对应的对象类型时,分别通过 getSingletonFactoryBeanForTypeCheck 方法获取单例工厂对象或 getNonSingletonFactoryBeanForTypeCheck 方法获取非单例工厂对象;若通过上述方法获取了工厂对象时,首先尝试通过 getTypeForFactoryBean 方法获取工厂对象对应类型,获取到时则直接返回该类型值,未获取到时,执行父类的 getTypeForFactoryBean 方法获取 mbd 关联工厂对象类型并返回;

之后若 mbd 没有工厂对象名但却拥有关联对象类型与工厂方法名,直接执行 getTypeForFactoryBeanFromMethod 方法通过对象工厂方法获取对应类型;最后通过 getFactoryBeanGeneric 方法获取 mbd 参数关联类型的泛型值,并在其不为 null 时直接返回该泛型值,否值直接返回 ResolvableType 类的 NONE 常量值;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Override
	protected ResolvableType getTypeForFactoryBean(String beanName, RootBeanDefinition mbd, boolean allowInit) {
		// Check if the bean definition itself has defined the type with an attribute
		ResolvableType result = getTypeForFactoryBeanFromAttributes(mbd);
		if (result != ResolvableType.NONE) {
			return result;
		}

		ResolvableType beanType =
				(mbd.hasBeanClass() ? ResolvableType.forClass(mbd.getBeanClass()) : ResolvableType.NONE);

		// For instance supplied beans try the target type and bean class
		if (mbd.getInstanceSupplier() != null) {
			result = getFactoryBeanGeneric(mbd.targetType);
			if (result.resolve() != null) {
				return result;
			}
			result = getFactoryBeanGeneric(beanType);
			if (result.resolve() != null) {
				return result;
			}
		}

		// Consider factory methods
		String factoryBeanName = mbd.getFactoryBeanName();
		String factoryMethodName = mbd.getFactoryMethodName();

		// Scan the factory bean methods
		if (factoryBeanName != null) {
			if (factoryMethodName != null) {
				// Try to obtain the FactoryBean's object type from its factory method
				// declaration without instantiating the containing bean at all.
				BeanDefinition factoryBeanDefinition = getBeanDefinition(factoryBeanName);
				Class<?> factoryBeanClass;
				if (factoryBeanDefinition instanceof AbstractBeanDefinition &&
						((AbstractBeanDefinition) factoryBeanDefinition).hasBeanClass()) {
					factoryBeanClass = ((AbstractBeanDefinition) factoryBeanDefinition).getBeanClass();
				}
				else {
					RootBeanDefinition fbmbd = getMergedBeanDefinition(factoryBeanName, factoryBeanDefinition);
					factoryBeanClass = determineTargetType(factoryBeanName, fbmbd);
				}
				if (factoryBeanClass != null) {
					result = getTypeForFactoryBeanFromMethod(factoryBeanClass, factoryMethodName);
					if (result.resolve() != null) {
						return result;
					}
				}
			}
			// If not resolvable above and the referenced factory bean doesn't exist yet,
			// exit here - we don't want to force the creation of another bean just to
			// obtain a FactoryBean's object type...
			if (!isBeanEligibleForMetadataCaching(factoryBeanName)) {
				return ResolvableType.NONE;
			}
		}

		// If we're allowed, we can create the factory bean and call getObjectType() early
		if (allowInit) {
			FactoryBean<?> factoryBean = (mbd.isSingleton() ?
					getSingletonFactoryBeanForTypeCheck(beanName, mbd) :
					getNonSingletonFactoryBeanForTypeCheck(beanName, mbd));
			if (factoryBean != null) {
				// Try to obtain the FactoryBean's object type from this early stage of the instance.
				Class<?> type = getTypeForFactoryBean(factoryBean);
				if (type != null) {
					return ResolvableType.forClass(type);
				}
				// No type found for shortcut FactoryBean instance:
				// fall back to full creation of the FactoryBean instance.
				return super.getTypeForFactoryBean(beanName, mbd, true);
			}
		}

		if (factoryBeanName == null && mbd.hasBeanClass() && factoryMethodName != null) {
			// No early bean instantiation possible: determine FactoryBean's type from
			// static factory method signature or from class inheritance hierarchy...
			return getTypeForFactoryBeanFromMethod(mbd.getBeanClass(), factoryMethodName);
		}
		result = getFactoryBeanGeneric(beanType);
		if (result.resolve() != null) {
			return result;
		}
		return ResolvableType.NONE;
	}
}

getFactoryBeanGeneric 方法在 type 参数为空时,直接返回 NONE 常量值,否则尝试将 type 转化为 FactoryBean 对象并调用其 getGeneric 方法获取其泛型值并返回;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	private ResolvableType getFactoryBeanGeneric(@Nullable ResolvableType type) {
		if (type == null) {
			return ResolvableType.NONE;
		}
		return type.as(FactoryBean.class).getGeneric();
	}
}

getTypeForFactoryBeanFromMethod 方法尝试从 beanClass 参数中查询 factoryMethodName 参数对应的所有对象工厂方法返回值的共同父类型并返回;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	private ResolvableType getTypeForFactoryBeanFromMethod(Class<?> beanClass, String factoryMethodName) {
		// CGLIB subclass methods hide generic parameters; look at the original user class.
		Class<?> factoryBeanClass = ClassUtils.getUserClass(beanClass);
		FactoryBeanMethodTypeFinder finder = new FactoryBeanMethodTypeFinder(factoryMethodName);
		ReflectionUtils.doWithMethods(factoryBeanClass, finder, ReflectionUtils.USER_DECLARED_METHODS);
		return finder.getResult();
	}
}

getSingletonFactoryBeanForTypeCheck 方法用于获取单例工厂对象快照来执行 getObjectType 方法获取其对应类型;其在 factoryBeanInstanceCache 属性已缓存该对象时,表明该对象已经创建过后直接返回缓存值;随后尝试 getSingleton 方法获取对应单例对象,在其为 FactoryBean 对象时直接返回;之后在 beanName 参数对应对象正在被创建或其 mbd 关联工厂对象正在创建时直接返回 null;随后使用 beforeSingletonCreation 将 beanName 标识为正在创建,同时一次尝试调用 resolveBeforeInstantiation 与 createBeanInstance 方法获取或创建对应的对象实例并将其保存到 instance 变量中;最后使用 getFactoryBean 方法验证获取到的 FactoryBean 对象,并在 bw 变量不为 null 时将其与 beanName 参数的映射保存到 factoryBeanInstanceCache 缓存中并返回获取到工厂对象;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Nullable
	private FactoryBean<?> getSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) {
		synchronized (getSingletonMutex()) {
			BeanWrapper bw = this.factoryBeanInstanceCache.get(beanName);
			if (bw != null) {
				return (FactoryBean<?>) bw.getWrappedInstance();
			}
			Object beanInstance = getSingleton(beanName, false);
			if (beanInstance instanceof FactoryBean) {
				return (FactoryBean<?>) beanInstance;
			}
			if (isSingletonCurrentlyInCreation(beanName) ||
					(mbd.getFactoryBeanName() != null && isSingletonCurrentlyInCreation(mbd.getFactoryBeanName()))) {
				return null;
			}

			Object instance;
			try {
				// Mark this bean as currently in creation, even if just partially.
				beforeSingletonCreation(beanName);
				// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
				instance = resolveBeforeInstantiation(beanName, mbd);
				if (instance == null) {
					bw = createBeanInstance(beanName, mbd, null);
					instance = bw.getWrappedInstance();
				}
			}
			catch (UnsatisfiedDependencyException ex) {
				// Don't swallow, probably misconfiguration...
				throw ex;
			}
			catch (BeanCreationException ex) {
				// Don't swallow a linkage error since it contains a full stacktrace on
				// first occurrence... and just a plain NoClassDefFoundError afterwards.
				if (ex.contains(LinkageError.class)) {
					throw ex;
				}
				// Instantiation failure, maybe too early...
				if (logger.isDebugEnabled()) {
					logger.debug("Bean creation exception on singleton FactoryBean type check: " + ex);
				}
				onSuppressedException(ex);
				return null;
			}
			finally {
				// Finished partial creation of this bean.
				afterSingletonCreation(beanName);
			}

			FactoryBean<?> fb = getFactoryBean(beanName, instance);
			if (bw != null) {
				this.factoryBeanInstanceCache.put(beanName, bw);
			}
			return fb;
		}
	}
}

getNonSingletonFactoryBeanForTypeCheck 方法用于获取非单例工厂对象快照来执行 getObjectType 方法获取其对应类型;其正在创建 beanName 参数对应的原型对象时直接返回 null,否则也是通过 resolveBeforeInstantiation 与 createBeanInstance 方法获取或创建对应工厂对象,最后调用 getFactoryBean 方法对创建对象进行验证并返回该对象;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Nullable
	private FactoryBean<?> getNonSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) {
		if (isPrototypeCurrentlyInCreation(beanName)) {
			return null;
		}

		Object instance;
		try {
			// Mark this bean as currently in creation, even if just partially.
			beforePrototypeCreation(beanName);
			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
			instance = resolveBeforeInstantiation(beanName, mbd);
			if (instance == null) {
				BeanWrapper bw = createBeanInstance(beanName, mbd, null);
				instance = bw.getWrappedInstance();
			}
		}
		catch (UnsatisfiedDependencyException ex) {
			// Don't swallow, probably misconfiguration...
			throw ex;
		}
		catch (BeanCreationException ex) {
			// Instantiation failure, maybe too early...
			if (logger.isDebugEnabled()) {
				logger.debug("Bean creation exception on non-singleton FactoryBean type check: " + ex);
			}
			onSuppressedException(ex);
			return null;
		}
		finally {
			// Finished partial creation of this bean.
			afterPrototypeCreation(beanName);
		}

		return getFactoryBean(beanName, instance);
	}
}

8 其他方法

8.1 createBeanInstance方法

createBeanInstance 方法在 mbd 参数拥有 instanceSupplier 属性,即拥有对象创建回调函数时,直接调用 obtainFromSupplier 方法通过该回调函数创建对象并返回;在其拥有对象工厂方法时,调用 instantiateUsingFactoryMethod 方法使用工厂方法创建对象并返回;在 args 参数为 null 且 mbd 参数的 resolvedConstructorOrFactoryMethod 方法不为空时,根据 mbd 参数的 constructorArgumentsResolved 属性来创建对象,在其为 true 时,直接使用 beanName 与 mbd 参数执行 autowireConstructor 方法通过构造器自动注入的方法创建对象并返回,在其为 false 时,调用 instantiateBean 方法创建对象并初始化;随后在 determineConstructorsFromBeanPostProcessors 方法为获取到对应构造方法、mbd 为构造器注入、mdb 参数的构造方法拥有参数或 args 参数不为空时,使用 beanName、 determineConstructorsFromBeanPostProcessors 获取到的构造方法数组、args 参数及 mbd 参数执行 autowireConstructor 方法创建对象并返回;之后在 mbd 参数拥有首选构造函数时,使用该构造函数执行 autowireConstructor 方法创建对象;最后直接执行 instantiateBean 方法创建对象并返回。

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
		// Make sure bean class is actually resolved at this point.
		Class<?> beanClass = resolveBeanClass(mbd, beanName);

		if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName,
					"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
		}

		Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
		if (instanceSupplier != null) {
			return obtainFromSupplier(instanceSupplier, beanName);
		}

		if (mbd.getFactoryMethodName() != null) {
			return instantiateUsingFactoryMethod(beanName, mbd, args);
		}

		// Shortcut when re-creating the same bean...
		boolean resolved = false;
		boolean autowireNecessary = false;
		if (args == null) {
			synchronized (mbd.constructorArgumentLock) {
				if (mbd.resolvedConstructorOrFactoryMethod != null) {
					resolved = true;
					autowireNecessary = mbd.constructorArgumentsResolved;
				}
			}
		}
		if (resolved) {
			if (autowireNecessary) {
				return autowireConstructor(beanName, mbd, null, null);
			}
			else {
				return instantiateBean(beanName, mbd);
			}
		}

		// Candidate constructors for autowiring?
		Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
		if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
				mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
			return autowireConstructor(beanName, mbd, ctors, args);
		}

		// Preferred constructors for default construction?
		ctors = mbd.getPreferredConstructors();
		if (ctors != null) {
			return autowireConstructor(beanName, mbd, ctors, null);
		}

		// No special handling: simply use no-arg constructor.
		return instantiateBean(beanName, mbd);
	}
}

obtainFromSupplier 方法首先执行 instanceSupplier 参数的 get 方法创建对象,在其为 null 时直接返回 NullBean 对象,否则使用 BeanWrapperImpl 对其进行封装并执行 initBeanWrapper 方法对其进行初始化并返回该封装值;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected BeanWrapper obtainFromSupplier(Supplier<?> instanceSupplier, String beanName) {
		Object instance;

		String outerBean = this.currentlyCreatedBean.get();
		this.currentlyCreatedBean.set(beanName);
		try {
			instance = instanceSupplier.get();
		}
		finally {
			if (outerBean != null) {
				this.currentlyCreatedBean.set(outerBean);
			}
			else {
				this.currentlyCreatedBean.remove();
			}
		}

		if (instance == null) {
			instance = new NullBean();
		}
		BeanWrapper bw = new BeanWrapperImpl(instance);
		initBeanWrapper(bw);
		return bw;
	}
}

determineConstructorsFromBeanPostProcessors 方法获取第一个 SmartInstantiationAwareBeanPostProcessor 后处理器对象的 determineCandidateConstructors 方法的非空执行结果并返回该值,未获取到则直接返回 null;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Nullable
	protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
			throws BeansException {

		if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
					SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
					Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
					if (ctors != null) {
						return ctors;
					}
				}
			}
		}
		return null;
	}
}

instantiateBean 方法首先使用 instantiationStrategy 属性的方法创建对象并使用 BeanWrapperImpl 对创建对象进行封装,同时使用 initBeanWrapper 方法初始化封装对象随后返回;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
		try {
			Object beanInstance;
			if (System.getSecurityManager() != null) {
				beanInstance = AccessController.doPrivileged(
						(PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, this),
						getAccessControlContext());
			}
			else {
				beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
			}
			BeanWrapper bw = new BeanWrapperImpl(beanInstance);
			initBeanWrapper(bw);
			return bw;
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
		}
	}
}

instantiateUsingFactoryMethod 与 autowireConstructor 方法分别通过 ConstructorResolver 对象的 instantiateUsingFactoryMethod 与 autowireConstructor 方法创建对象并返回;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected BeanWrapper instantiateUsingFactoryMethod(
			String beanName, RootBeanDefinition mbd, @Nullable Object[] explicitArgs) {

		return new ConstructorResolver(this).instantiateUsingFactoryMethod(beanName, mbd, explicitArgs);
	}

	protected BeanWrapper autowireConstructor(
			String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] ctors, @Nullable Object[] explicitArgs) {

		return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs);
	}
}

8.2 getObjectForBeanInstance方法

getObjectForBeanInstance 方法将父对象的 getObjectForBeanInstance 方法扩展为将 beanName 添加到当前正在创建的对象的依赖的功能。

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Override
	protected Object getObjectForBeanInstance(
			Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {

		String currentlyCreatedBean = this.currentlyCreatedBean.get();
		if (currentlyCreatedBean != null) {
			registerDependentBean(beanName, currentlyCreatedBean);
		}

		return super.getObjectForBeanInstance(beanInstance, name, beanName, mbd);
	}
}

8.3 populateBean方法

populateBean 方法为 bw 封装对象填充属性;其在 bw 为 null 且 mbd 没有任何属性时直接返回;随后在 mbd 参数为非合成注册表且拥有 InstantiationAwareBeanPostProcessor 后处理器时,依次为 bw 参数执行 postProcessAfterInstantiation 方法,一旦执行结果出现了 false 则会直接返回;随后根据 mbd 参数的自动注入模式解析注入属性,在其为 AUTOWIRE_BY_NAME 根据名称注入时,调用 autowireByName 获取注入属性值,为 AUTOWIRE_BY_TYPE 时调用 autowireByType 获取属性注入属性值;在当前拥有 InstantiationAwareBeanPostProcessor 后处理器时,首先执行 postProcessProperties 方法对获取的属性的进行后处理然后使用处理结果更新属性注入值,其中值得注意的是,若处理后的结果为 null 时,会使用 filterPropertyDescriptorsForDependencyCheck 方法获取的依赖过滤器执行 postProcessPropertyValues 方法对结果进行处理,若处理结果依然为 null,则也是中断注入流程并返回;之后若需要进行依赖验证,则会调用 checkDependencies 方法进行验证,最后在获取到的属性值不为 null 时,调用 applyPropertyValues 方法将其注入到 bw 参数中;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
		if (bw == null) {
			if (mbd.hasPropertyValues()) {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
			}
			else {
				// Skip property population phase for null instance.
				return;
			}
		}

		// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
		// state of the bean before properties are set. This can be used, for example,
		// to support styles of field injection.
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						return;
					}
				}
			}
		}

		PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

		int resolvedAutowireMode = mbd.getResolvedAutowireMode();
		if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
			// Add property values based on autowire by name if applicable.
			if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs);
			}
			// Add property values based on autowire by type if applicable.
			if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs);
			}
			pvs = newPvs;
		}

		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

		PropertyDescriptor[] filteredPds = null;
		if (hasInstAwareBpps) {
			if (pvs == null) {
				pvs = mbd.getPropertyValues();
			}
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
					if (pvsToUse == null) {
						if (filteredPds == null) {
							filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
						}
						pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
						if (pvsToUse == null) {
							return;
						}
					}
					pvs = pvsToUse;
				}
			}
		}
		if (needsDepCheck) {
			if (filteredPds == null) {
				filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
			}
			checkDependencies(beanName, mbd, filteredPds, pvs);
		}

		if (pvs != null) {
			applyPropertyValues(beanName, mbd, bw, pvs);
		}
	}
}

autowireByName 方法遍历通过 unsatisfiedNonSimpleProperties 方法获取 bw 方法中还未完成填充的属性名数组,并将其中当前工厂拥有的对象保存到 pvs 参数中,并将该属性名注册为 beanName 参数的依赖;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected void autowireByName(
			String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

		String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
		for (String propertyName : propertyNames) {
			if (containsBean(propertyName)) {
				Object bean = getBean(propertyName);
				pvs.add(propertyName, bean);
				registerDependentBean(propertyName, beanName);
				if (logger.isTraceEnabled()) {
					logger.trace("Added autowiring by name from bean name '" + beanName +
							"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
				}
			}
			else {
				if (logger.isTraceEnabled()) {
					logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
							"' by name: no matching bean found");
				}
			}
		}
	}
}

autowireByType 方法也是遍历通过 unsatisfiedNonSimpleProperties 方法获取 bw 方法中还未完成填充的属性名数组,依次通过 resolveDependency 方法获取属性对应的对象,并在其不为 null 时将其保存到 pvs 参数中,并将自动注入对象名依次保存为 beanName 参数的依赖名;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected void autowireByType(
			String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

		TypeConverter converter = getCustomTypeConverter();
		if (converter == null) {
			converter = bw;
		}

		Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
		String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
		for (String propertyName : propertyNames) {
			try {
				PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
				// Don't try autowiring by type for type Object: never makes sense,
				// even if it technically is a unsatisfied, non-simple property.
				if (Object.class != pd.getPropertyType()) {
					MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
					// Do not allow eager init for type matching in case of a prioritized post-processor.
					boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered);
					DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
					Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
					if (autowiredArgument != null) {
						pvs.add(propertyName, autowiredArgument);
					}
					for (String autowiredBeanName : autowiredBeanNames) {
						registerDependentBean(autowiredBeanName, beanName);
						if (logger.isTraceEnabled()) {
							logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
									propertyName + "' to bean named '" + autowiredBeanName + "'");
						}
					}
					autowiredBeanNames.clear();
				}
			}
			catch (BeansException ex) {
				throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
			}
		}
	}
}

unsatisfiedNonSimpleProperties 方法用于获取 bw 中未完成填充且拥有写方法的非简单依赖属性名数组;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) {
		Set<String> result = new TreeSet<>();
		PropertyValues pvs = mbd.getPropertyValues();
		PropertyDescriptor[] pds = bw.getPropertyDescriptors();
		for (PropertyDescriptor pd : pds) {
			if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) &&
					!BeanUtils.isSimpleProperty(pd.getPropertyType())) {
				result.add(pd.getName());
			}
		}
		return StringUtils.toStringArray(result);
	}
}

filterPropertyDescriptorsForDependencyCheck 方法用于获取 bw 参数对应的过滤后的依赖对象数组;其首先尝试从 filteredPropertyDescriptorsCache 缓存中获取,在其结果不为 null 时直接返回;否则会通过 filterPropertyDescriptorsForDependencyCheck 方法解析获取对应依赖对象数组,斌在 cache 参数为 true 时将其保存到 filteredPropertyDescriptorsCache 缓存中,并返回;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw, boolean cache) {
		PropertyDescriptor[] filtered = this.filteredPropertyDescriptorsCache.get(bw.getWrappedClass());
		if (filtered == null) {
			filtered = filterPropertyDescriptorsForDependencyCheck(bw);
			if (cache) {
				PropertyDescriptor[] existing =
						this.filteredPropertyDescriptorsCache.putIfAbsent(bw.getWrappedClass(), filtered);
				if (existing != null) {
					filtered = existing;
				}
			}
		}
		return filtered;
	}
}

filterPropertyDescriptorsForDependencyCheck 方法通过 isExcludedFromDependencyCheck 方法排除对应的依赖对象并返回;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw) {
		List<PropertyDescriptor> pds = new ArrayList<>(Arrays.asList(bw.getPropertyDescriptors()));
		pds.removeIf(this::isExcludedFromDependencyCheck);
		return pds.toArray(new PropertyDescriptor[0]);
	}
}

isExcludedFromDependencyCheck 方法在 AutowireUtils 的 isExcludedFromDependencyCheck 方法结果、ignoredDependencyTypes 属性包含 pd 对应类型或 AutowireUtils 的 isSetterDefinedInInterface 方法执行结果为 true 时返回 true;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected boolean isExcludedFromDependencyCheck(PropertyDescriptor pd) {
		return (AutowireUtils.isExcludedFromDependencyCheck(pd) ||
				this.ignoredDependencyTypes.contains(pd.getPropertyType()) ||
				AutowireUtils.isSetterDefinedInInterface(pd, this.ignoredDependencyInterfaces));
	}
}

checkDependencies 方法验证 pds 中是否存在未赋值但满足 mbd 参数验证模式的元素对象;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected void checkDependencies(
			String beanName, AbstractBeanDefinition mbd, PropertyDescriptor[] pds, @Nullable PropertyValues pvs)
			throws UnsatisfiedDependencyException {

		int dependencyCheck = mbd.getDependencyCheck();
		for (PropertyDescriptor pd : pds) {
			if (pd.getWriteMethod() != null && (pvs == null || !pvs.contains(pd.getName()))) {
				boolean isSimple = BeanUtils.isSimpleProperty(pd.getPropertyType());
				boolean unsatisfied = (dependencyCheck == AbstractBeanDefinition.DEPENDENCY_CHECK_ALL) ||
						(isSimple && dependencyCheck == AbstractBeanDefinition.DEPENDENCY_CHECK_SIMPLE) ||
						(!isSimple && dependencyCheck == AbstractBeanDefinition.DEPENDENCY_CHECK_OBJECTS);
				if (unsatisfied) {
					throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, pd.getName(),
							"Set this property value or disable dependency checking for this bean.");
				}
			}
		}
	}
}

applyPropertyValues 方法在 pvs 参数为空时直接返回,随后在 pvs 参数为 MutablePropertyValues 对象且其已完成转换则直接调用 bw 参数的 setPropertyValues 方法设置参数并返回,否则获取 pvs 参数值列表并将其保存到 original 变量中;随后使用 typeConverter 属性(该属性为 null 时使用 bw 参数)、beanName、mbd 及当前对象创建 BeanDefinitionValueResolver 对象注册表属性值解析器;随后对 original 变量进行遍历,在元素已完成转换时,将其保存到 deepCopy 变量之中,在元素值为 INSTANCE 对象时,创建 DependencyDescriptor 对象来更新属性对象值,随后尝试使用创建的属性解析器尝试解析属性值,并将当前属性为可写且不为索引或嵌套属性时将 convertible 变量更新为 true,在该值为 true 时,调用 convertForProperty 方法将解析值的转化值保存到 convertedValue 变量值,否则该值为解析值;之后在解析值与元素值相同时,将元素对象保存到 deepCopy 变量中,同时在 convertible 为 true 时,将转换后值保存到当前元素中,在 convertible 为 true、原值为非动态字符串且转换值不为集合或数组时,将转换后值保存到当前元素中并元素对象保存到 deepCopy 变量中,否则将 resolveNecessary 变量置为 true 同时使用元素对象与转换值创建 PropertyValue 对象并添加到 deepCopy 变量中;最后在 mpvs 变量不为 null 且 resolveNecessary 属性为 false 时将其标识为已完成转换同时使用 deepCopy 变量值更新 bw 参数的属性值。

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
		if (pvs.isEmpty()) {
			return;
		}

		if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
			((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
		}

		MutablePropertyValues mpvs = null;
		List<PropertyValue> original;

		if (pvs instanceof MutablePropertyValues) {
			mpvs = (MutablePropertyValues) pvs;
			if (mpvs.isConverted()) {
				// Shortcut: use the pre-converted values as-is.
				try {
					bw.setPropertyValues(mpvs);
					return;
				}
				catch (BeansException ex) {
					throw new BeanCreationException(
							mbd.getResourceDescription(), beanName, "Error setting property values", ex);
				}
			}
			original = mpvs.getPropertyValueList();
		}
		else {
			original = Arrays.asList(pvs.getPropertyValues());
		}

		TypeConverter converter = getCustomTypeConverter();
		if (converter == null) {
			converter = bw;
		}
		BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

		// Create a deep copy, resolving any references for values.
		List<PropertyValue> deepCopy = new ArrayList<>(original.size());
		boolean resolveNecessary = false;
		for (PropertyValue pv : original) {
			if (pv.isConverted()) {
				deepCopy.add(pv);
			}
			else {
				String propertyName = pv.getName();
				Object originalValue = pv.getValue();
				if (originalValue == AutowiredPropertyMarker.INSTANCE) {
					Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod();
					if (writeMethod == null) {
						throw new IllegalArgumentException("Autowire marker for property without write method: " + pv);
					}
					originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true);
				}
				Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
				Object convertedValue = resolvedValue;
				boolean convertible = bw.isWritableProperty(propertyName) &&
						!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
				if (convertible) {
					convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
				}
				// Possibly store converted value in merged bean definition,
				// in order to avoid re-conversion for every created bean instance.
				if (resolvedValue == originalValue) {
					if (convertible) {
						pv.setConvertedValue(convertedValue);
					}
					deepCopy.add(pv);
				}
				else if (convertible && originalValue instanceof TypedStringValue &&
						!((TypedStringValue) originalValue).isDynamic() &&
						!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
					pv.setConvertedValue(convertedValue);
					deepCopy.add(pv);
				}
				else {
					resolveNecessary = true;
					deepCopy.add(new PropertyValue(pv, convertedValue));
				}
			}
		}
		if (mpvs != null && !resolveNecessary) {
			mpvs.setConverted();
		}

		// Set our (possibly massaged) deep copy.
		try {
			bw.setPropertyValues(new MutablePropertyValues(deepCopy));
		}
		catch (BeansException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Error setting property values", ex);
		}
	}
}

convertForProperty 方法在 converter 参数为 BeanWrapperImpl 对象时,调用其 convertForProperty 方法转换属性值并返回;否则调用 converter 参数的 convertIfNecessary 参数转换属性值并返回。

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	@Nullable
	private Object convertForProperty(
			@Nullable Object value, String propertyName, BeanWrapper bw, TypeConverter converter) {

		if (converter instanceof BeanWrapperImpl) {
			return ((BeanWrapperImpl) converter).convertForProperty(value, propertyName);
		}
		else {
			PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
			MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
			return converter.convertIfNecessary(value, pd.getPropertyType(), methodParam);
		}
	}
}

8.4 initializeBean方法

initializeBean 方法首先调用 invokeAwareMethods 方法执行 aware 相关方法,随后在 mbd 对象注册表不是组合对象时,调用 applyBeanPostProcessorsBeforeInitialization 执行初始化前处理器,随后调用 invokeInitMethods 方法执行初始化方法,在初始化完成后,在 mbd 对象注册表不是组合对象时,调用 applyBeanPostProcessorsAfterInitialization 执行初始化后处理器,并返回初始化值。

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareMethods(beanName, bean);
				return null;
			}, getAccessControlContext());
		}
		else {
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					(mbd != null ? mbd.getResourceDescription() : null),
					beanName, "Invocation of init method failed", ex);
		}
		if (mbd == null || !mbd.isSynthetic()) {
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}
}

invokeAwareMethods 方法执行 BeanNameAware 接口的 setBeanName 方法、BeanClassLoaderAware 接口的 setBeanClassLoader 方法及 BeanFactoryAware 接口的 setBeanFactory 方法;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	private void invokeAwareMethods(String beanName, Object bean) {
		if (bean instanceof Aware) {
			if (bean instanceof BeanNameAware) {
				((BeanNameAware) bean).setBeanName(beanName);
			}
			if (bean instanceof BeanClassLoaderAware) {
				ClassLoader bcl = getBeanClassLoader();
				if (bcl != null) {
					((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
				}
			}
			if (bean instanceof BeanFactoryAware) {
				((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
			}
		}
	}
}

invokeInitMethods 方法在 bean 参数为 InitializingBean 对象且其外部没有 afterPropertiesSet 初始化方法时,执行其的 afterPropertiesSet 方法,随后通过 invokeCustomInitMethod 方法执行 mbd 关联的所有初始化方法;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
			throws Throwable {

		boolean isInitializingBean = (bean instanceof InitializingBean);
		if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
			if (logger.isTraceEnabled()) {
				logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
			}
			if (System.getSecurityManager() != null) {
				try {
					AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
						((InitializingBean) bean).afterPropertiesSet();
						return null;
					}, getAccessControlContext());
				}
				catch (PrivilegedActionException pae) {
					throw pae.getException();
				}
			}
			else {
				((InitializingBean) bean).afterPropertiesSet();
			}
		}

		if (mbd != null && bean.getClass() != NullBean.class) {
			String initMethodName = mbd.getInitMethodName();
			if (StringUtils.hasLength(initMethodName) &&
					!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
					!mbd.isExternallyManagedInitMethod(initMethodName)) {
				invokeCustomInitMethod(beanName, bean, mbd);
			}
		}
	}
}

invokeCustomInitMethod 方法在 bean 参数中拥有对应的初始化方法时,将其状态变为可读并执行;

java 复制代码
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
	protected void invokeCustomInitMethod(String beanName, Object bean, RootBeanDefinition mbd)
			throws Throwable {

		String initMethodName = mbd.getInitMethodName();
		Assert.state(initMethodName != null, "No init method set");
		Method initMethod = (mbd.isNonPublicAccessAllowed() ?
				BeanUtils.findMethod(bean.getClass(), initMethodName) :
				ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));

		if (initMethod == null) {
			if (mbd.isEnforceInitMethod()) {
				throw new BeanDefinitionValidationException("Could not find an init method named '" +
						initMethodName + "' on bean with name '" + beanName + "'");
			}
			else {
				if (logger.isTraceEnabled()) {
					logger.trace("No default init method named '" + initMethodName +
							"' found on bean with name '" + beanName + "'");
				}
				// Ignore non-existent default lifecycle methods.
				return;
			}
		}

		if (logger.isTraceEnabled()) {
			logger.trace("Invoking init method  '" + initMethodName + "' on bean with name '" + beanName + "'");
		}
		Method methodToInvoke = ClassUtils.getInterfaceMethodIfPossible(initMethod);

		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				ReflectionUtils.makeAccessible(methodToInvoke);
				return null;
			});
			try {
				AccessController.doPrivileged((PrivilegedExceptionAction<Object>)
						() -> methodToInvoke.invoke(bean), getAccessControlContext());
			}
			catch (PrivilegedActionException pae) {
				InvocationTargetException ex = (InvocationTargetException) pae.getException();
				throw ex.getTargetException();
			}
		}
		else {
			try {
				ReflectionUtils.makeAccessible(methodToInvoke);
				methodToInvoke.invoke(bean);
			}
			catch (InvocationTargetException ex) {
				throw ex.getTargetException();
			}
		}
	}
}

DefaultListableBeanFactory

AbstractAutowireCapableBeanFactory 类在继承了 AbstractBeanFactory 类并实现了 AutowireCapableBeanFactory 接口,其默认实现 bean 对象的创建,其提供了对象创建属性填充,联机及初始化相关功能;

1 属性及构造方法

1.1 静态常量

javaxInjectProviderClass 常量为 JSR-330 API 支持类常量,其在静态代码块中尝试初始化为 javax.inject.Provider 类,若未获取到则将其初始化为 null;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {

	@Nullable
	private static Class<?> javaxInjectProviderClass;

	static {
		try {
			javaxInjectProviderClass =
					ClassUtils.forName("javax.inject.Provider", DefaultListableBeanFactory.class.getClassLoader());
		}
		catch (ClassNotFoundException ex) {
			// JSR-330 API not available - Provider interface simply not supported then.
			javaxInjectProviderClass = null;
		}
	}
}

serializableFactories 常量保存的则是 id 与 DefaultListableBeanFactory 对象引用的映射 Map 对象;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	private static final Map<String, Reference<DefaultListableBeanFactory>> serializableFactories =
			new ConcurrentHashMap<>(8);
}

1.2 类属性

serializationId 属性为当前 DefaultListableBeanFactory 工厂的 id 值,其 set 方法在参数为 null 时,将其与当前对象映射保存到 serializableFactories 常量中,在其为 null 但该属性不为 null 时则会将其映射从 serializableFactories 常量中移除,最后将 serializationId 属性更新为 serializationId 参数值;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Nullable
	private String serializationId;

	public void setSerializationId(@Nullable String serializationId) {
		if (serializationId != null) {
			serializableFactories.put(serializationId, new WeakReference<>(this));
		}
		else if (this.serializationId != null) {
			serializableFactories.remove(this.serializationId);
		}
		this.serializationId = serializationId;
	}

	@Nullable
	public String getSerializationId() {
		return this.serializationId;
	}
}

allowBeanDefinitionOverriding 属性标识的则是是否允许重写同名对象,默认为 true,表明允许同名对象的重写;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	private boolean allowBeanDefinitionOverriding = true;

	public void setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding) {
		this.allowBeanDefinitionOverriding = allowBeanDefinitionOverriding;
	}

	public boolean isAllowBeanDefinitionOverriding() {
		return this.allowBeanDefinitionOverriding;
	}
}

allowEagerClassLoading 属性标识是否允许快速加载懒加载类;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	private boolean allowBeanDefinitionOverriding = true;

	public void setAllowBeanDefinitionOverriding(boolean allowBeanDefinitionOverriding) {
		this.allowBeanDefinitionOverriding = allowBeanDefinitionOverriding;
	}

	public boolean isAllowBeanDefinitionOverriding() {
		return this.allowBeanDefinitionOverriding;
	}
}

dependencyComparator 属性保存的则是对象依赖排序对象;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Nullable
	private Comparator<Object> dependencyComparator;

	public void setDependencyComparator(@Nullable Comparator<Object> dependencyComparator) {
		this.dependencyComparator = dependencyComparator;
	}

	@Nullable
	public Comparator<Object> getDependencyComparator() {
		return this.dependencyComparator;
	}
}

autowireCandidateResolver 属性为自动注入候选项解析器对象,默认使用 SimpleAutowireCandidateResolver 类型解析器,使用 set 方法设置的过程中,若 autowireCandidateResolver 参数为 BeanFactoryAware 对象时,将其对象工厂设置为当前对象之后才会更新 autowireCandidateResolver 属性值;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	private AutowireCandidateResolver autowireCandidateResolver = SimpleAutowireCandidateResolver.INSTANCE;

	public void setAutowireCandidateResolver(AutowireCandidateResolver autowireCandidateResolver) {
		Assert.notNull(autowireCandidateResolver, "AutowireCandidateResolver must not be null");
		if (autowireCandidateResolver instanceof BeanFactoryAware) {
			if (System.getSecurityManager() != null) {
				AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
					((BeanFactoryAware) autowireCandidateResolver).setBeanFactory(this);
					return null;
				}, getAccessControlContext());
			}
			else {
				((BeanFactoryAware) autowireCandidateResolver).setBeanFactory(this);
			}
		}
		this.autowireCandidateResolver = autowireCandidateResolver;
	}

	public AutowireCandidateResolver getAutowireCandidateResolver() {
		return this.autowireCandidateResolver;
	}
}

resolvableDependencies 、beanDefinitionMap 及 mergedBeanDefinitionHolders 属性用于存储完成解析的类型与对象、对象名与对象注册表及对象名与对象注册表保存器映射;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	private final Map<Class<?>, Object> resolvableDependencies = new ConcurrentHashMap<>(16);

	private final Map<Class<?>, Object> resolvableDependencies = new ConcurrentHashMap<>(16);

	private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
}

allBeanNamesByType 与 singletonBeanNamesByType 属性分别为类型与对象名数组及类型与单例对象名映射;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	private final Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<>(64);

	private final Map<Class<?>, String[]> singletonBeanNamesByType = new ConcurrentHashMap<>(64);
}

beanDefinitionNames 与 manualSingletonNames 属性保存的则是按注册顺序保存的对象名及手动注册单例对象名列表;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	private volatile List<String> beanDefinitionNames = new ArrayList<>(256);

	private volatile Set<String> manualSingletonNames = new LinkedHashSet<>(16);
}

frozenBeanDefinitionNames 与 configurationFrozen 属性分别保存配置冻结时对象名数组及当前配置是否已冻结;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Nullable
	private volatile String[] frozenBeanDefinitionNames;

	private volatile boolean configurationFrozen;
}

1.3 构造方法

两个构造方法都是直接调用父类的构造方法不做其他任意操作;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	public DefaultListableBeanFactory() {
		super();
	}

	public DefaultListableBeanFactory(@Nullable BeanFactory parentBeanFactory) {
		super(parentBeanFactory);
	}
}

2 对象工厂方法的重写

2.1 getBean 方法

getBean 方法在完成了对 requiredType 参数进行非空验证后,调用 resolveBean 方法解析对象,并在其解析结果不为空时返回,否则抛出 NoSuchBeanDefinitionException 异常;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public <T> T getBean(Class<T> requiredType) throws BeansException {
		return getBean(requiredType, (Object[]) null);
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T getBean(Class<T> requiredType, @Nullable Object... args) throws BeansException {
		Assert.notNull(requiredType, "Required type must not be null");
		Object resolved = resolveBean(ResolvableType.forRawClass(requiredType), args, false);
		if (resolved == null) {
			throw new NoSuchBeanDefinitionException(requiredType);
		}
		return (T) resolved;
	}
}

2.2 getBeanProvider 方法

getBeanProvider 方法中返回了该方法中实现的 BeanObjectProvider 对象,其中 getObject、getIfAvailable 及 getIfUnique 四个方法都是直接调用 resolveBean 方法获取对象并返回,其中两个 getObject 方法在 resolveBean 方法结果为 null 时抛出 NoSuchBeanDefinitionException 异常,另外两个方法则不会;最后两个方法分别为获取 requiredType 对应对象数组流,他们之间的差别在于 orderedStream 方法获取的流为顺序流,他们首先都是通过 getBeanNamesForTypedStream 方法获取对应的对象数组,并在过滤完其中的 NullBean 对象后排序或直接返回;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public <T> ObjectProvider<T> getBeanProvider(Class<T> requiredType) {
		Assert.notNull(requiredType, "Required type must not be null");
		return getBeanProvider(ResolvableType.forRawClass(requiredType));
	}

	@Override
	public <T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType) {
		return new BeanObjectProvider<T>() {
			@Override
			public T getObject() throws BeansException {
				T resolved = resolveBean(requiredType, null, false);
				if (resolved == null) {
					throw new NoSuchBeanDefinitionException(requiredType);
				}
				return resolved;
			}
			@Override
			public T getObject(Object... args) throws BeansException {
				T resolved = resolveBean(requiredType, args, false);
				if (resolved == null) {
					throw new NoSuchBeanDefinitionException(requiredType);
				}
				return resolved;
			}
			@Override
			@Nullable
			public T getIfAvailable() throws BeansException {
				return resolveBean(requiredType, null, false);
			}
			@Override
			@Nullable
			public T getIfUnique() throws BeansException {
				return resolveBean(requiredType, null, true);
			}
			@SuppressWarnings("unchecked")
			@Override
			public Stream<T> stream() {
				return Arrays.stream(getBeanNamesForTypedStream(requiredType))
						.map(name -> (T) getBean(name))
						.filter(bean -> !(bean instanceof NullBean));
			}
			@SuppressWarnings("unchecked")
			@Override
			public Stream<T> orderedStream() {
				String[] beanNames = getBeanNamesForTypedStream(requiredType);
				if (beanNames.length == 0) {
					return Stream.empty();
				}
				Map<String, T> matchingBeans = new LinkedHashMap<>(beanNames.length);
				for (String beanName : beanNames) {
					Object beanInstance = getBean(beanName);
					if (!(beanInstance instanceof NullBean)) {
						matchingBeans.put(beanName, (T) beanInstance);
					}
				}
				Stream<T> stream = matchingBeans.values().stream();
				return stream.sorted(adaptOrderComparator(matchingBeans));
			}
		};
	}
}

2.3 resolveBean 方法

resolveBean 方法首先尝试通过 resolveNamedBean 方法获取对象,获取到了直接返回;否则在 parent 父对象工厂为空时直接返回 null,在父对象工厂为 DefaultListableBeanFactory 对象时,调用其 resolveBean 方法解析对象并返回,否则则会通过父对象工厂获取其对应的 ObjectProvider 对象,并使用其对应方法创建对象并返回。

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Nullable
	private <T> T resolveBean(ResolvableType requiredType, @Nullable Object[] args, boolean nonUniqueAsNull) {
		NamedBeanHolder<T> namedBean = resolveNamedBean(requiredType, args, nonUniqueAsNull);
		if (namedBean != null) {
			return namedBean.getBeanInstance();
		}
		BeanFactory parent = getParentBeanFactory();
		if (parent instanceof DefaultListableBeanFactory) {
			return ((DefaultListableBeanFactory) parent).resolveBean(requiredType, args, nonUniqueAsNull);
		}
		else if (parent != null) {
			ObjectProvider<T> parentProvider = parent.getBeanProvider(requiredType);
			if (args != null) {
				return parentProvider.getObject(args);
			}
			else {
				return (nonUniqueAsNull ? parentProvider.getIfUnique() : parentProvider.getIfAvailable());
			}
		}
		return null;
	}
}

2.4 getBeanNamesForTypedStream 方法

getBeanNamesForTypedStream 方法直接调用 BeanFactoryUtils 的 beanNamesForTypeIncludingAncestors 方法获取 requiredType 参数对应的对象名数组;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	private String[] getBeanNamesForTypedStream(ResolvableType requiredType) {
		return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this, requiredType);
	}
}

beanNamesForTypeIncludingAncestors 方法首先对 lbf 参数进行非空验证,通过验证后通过其 getBeanNamesForType 方法获取 type 参数对应的对象名数组,并在 lbf 参数为 HierarchicalBeanFactory 对象且其父对象工厂为 ListableBeanFactory 对象时,递归调用其父对象工厂获取其 type 参数对应的对象名数组并调用 mergeNamesWithParent 方法将其与 lbf 参数中获取到的对象名数组进行去重合并并返回;

java 复制代码
public abstract class BeanFactoryUtils {
	public static String[] beanNamesForTypeIncludingAncestors(ListableBeanFactory lbf, ResolvableType type) {
		Assert.notNull(lbf, "ListableBeanFactory must not be null");
		String[] result = lbf.getBeanNamesForType(type);
		if (lbf instanceof HierarchicalBeanFactory) {
			HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
			if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
				String[] parentResult = beanNamesForTypeIncludingAncestors(
						(ListableBeanFactory) hbf.getParentBeanFactory(), type);
				result = mergeNamesWithParent(result, parentResult, hbf);
			}
		}
		return result;
	}

	private static String[] mergeNamesWithParent(String[] result, String[] parentResult, HierarchicalBeanFactory hbf) {
		if (parentResult.length == 0) {
			return result;
		}
		List<String> merged = new ArrayList<>(result.length + parentResult.length);
		merged.addAll(Arrays.asList(result));
		for (String beanName : parentResult) {
			if (!merged.contains(beanName) && !hbf.containsLocalBean(beanName)) {
				merged.add(beanName);
			}
		}
		return StringUtils.toStringArray(merged);
	}
}

3 ListableBeanFactory 接口方法实现

3.1 containsBeanDefinition 方法

containsBeanDefinition 方法在通过对 beanName 参数的非空验证后直接返回 beanDefinitionMap 属性中是否拥有该元素映射;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public boolean containsBeanDefinition(String beanName) {
		Assert.notNull(beanName, "Bean name must not be null");
		return this.beanDefinitionMap.containsKey(beanName);
	}
}

3.2 getBeanDefinitionCount 方法

getBeanDefinitionCount 方法直接返回 beanDefinitionMap 属性的大小;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public int getBeanDefinitionCount() {
		return this.beanDefinitionMap.size();
	}
}

3.3 getBeanDefinitionNames 方法

getBeanDefinitionNames 方法在 frozenBeanDefinitionNames 属性不为空时,直接返回该属性的克隆值,否则则会将 beanDefinitionNames 属性转换为字符串数组并返回;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public String[] getBeanDefinitionNames() {
		String[] frozenNames = this.frozenBeanDefinitionNames;
		if (frozenNames != null) {
			return frozenNames.clone();
		}
		else {
			return StringUtils.toStringArray(this.beanDefinitionNames);
		}
	}
}

3.4 getBeanNamesForType 方法

带 ResolvableType 类型参数的 getBeanNamesForType 方法在其解析类型值不为 null 且不为泛型对象时,直接执行带 Class 类型参数的 getBeanNamesForType 方法获取对应对象名数组并返回,否则 doGetBeanNamesForType 方法获取对应对象名数组并返回;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public String[] getBeanNamesForType(ResolvableType type) {
		return getBeanNamesForType(type, true, true);
	}

	@Override
	public String[] getBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
		Class<?> resolved = type.resolve();
		if (resolved != null && !type.hasGenerics()) {
			return getBeanNamesForType(resolved, includeNonSingletons, allowEagerInit);
		}
		else {
			return doGetBeanNamesForType(type, includeNonSingletons, allowEagerInit);
		}
	}
}

带 Class 类型参数的 getBeanNamesForType 方法在当前对象工厂配置还未冻结、type 为 null 或不允许快速初始化时,直接调用 doGetBeanNamesForType 方法并返回,随后根据是否需要包含单例对象名尝试从缓存中获取对应对象名数组,在其缓存结果不为 null 时直接返回;在现在还未缓存时则也会调用 doGetBeanNamesForType 获取对应对象名数组,并在其可被缓存时将其保存到 allBeanNamesByType 或 singletonBeanNamesByType 缓存中并返回;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public String[] getBeanNamesForType(@Nullable Class<?> type) {
		return getBeanNamesForType(type, true, true);
	}

	@Override
	public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
		if (!isConfigurationFrozen() || type == null || !allowEagerInit) {
			return doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, allowEagerInit);
		}
		Map<Class<?>, String[]> cache =
				(includeNonSingletons ? this.allBeanNamesByType : this.singletonBeanNamesByType);
		String[] resolvedBeanNames = cache.get(type);
		if (resolvedBeanNames != null) {
			return resolvedBeanNames;
		}
		resolvedBeanNames = doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, true);
		if (ClassUtils.isCacheSafe(type, getBeanClassLoader())) {
			cache.put(type, resolvedBeanNames);
		}
		return resolvedBeanNames;
	}
}

doGetBeanNamesForType 方法首先查询 beanDefinitionNames 属性中的非别名元素值,在该元素对应 RootBeanDefinition 注册表非抽象类且需要立即加载时,判断其是否的对象工厂对象,在不为对象工厂且 includeNonSingletons 属性为 true 或其对应单例对象时将 matchFound 局部变量更新为当前元素是否与其类型相匹配,否则只有在 includeNonSingletons 属性为 true、当前元素内部对象不为懒加载或其为单例对象时,通过 isTypeMatch 方法来更新 matchFound 局部变量值并在其不匹配时判断其当前元素是否为指定类型对象工厂,最后在能匹配上时将该元素保存到 result 属性中;在之后将 manualSingletonNames 属性中与 type 参数相匹配的元素添加到 result 变量中,然后在通过上述操作保存完了所有匹配对象名时将 result 变量转换为数组并返回。

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
		List<String> result = new ArrayList<>();

		// Check all bean definitions.
		for (String beanName : this.beanDefinitionNames) {
			// Only consider bean as eligible if the bean name is not defined as alias for some other bean.
			if (!isAlias(beanName)) {
				try {
					RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
					// Only check bean definition if it is complete.
					if (!mbd.isAbstract() && (allowEagerInit ||
							(mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading()) &&
									!requiresEagerInitForType(mbd.getFactoryBeanName()))) {
						boolean isFactoryBean = isFactoryBean(beanName, mbd);
						BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
						boolean matchFound = false;
						boolean allowFactoryBeanInit = (allowEagerInit || containsSingleton(beanName));
						boolean isNonLazyDecorated = (dbd != null && !mbd.isLazyInit());
						if (!isFactoryBean) {
							if (includeNonSingletons || isSingleton(beanName, mbd, dbd)) {
								matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
							}
						}
						else {
							if (includeNonSingletons || isNonLazyDecorated ||
									(allowFactoryBeanInit && isSingleton(beanName, mbd, dbd))) {
								matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
							}
							if (!matchFound) {
								// In case of FactoryBean, try to match FactoryBean instance itself next.
								beanName = FACTORY_BEAN_PREFIX + beanName;
								matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
							}
						}
						if (matchFound) {
							result.add(beanName);
						}
					}
				}
				catch (CannotLoadBeanClassException | BeanDefinitionStoreException ex) {
					if (allowEagerInit) {
						throw ex;
					}
					// Probably a placeholder: let's ignore it for type matching purposes.
					LogMessage message = (ex instanceof CannotLoadBeanClassException ?
							LogMessage.format("Ignoring bean class loading failure for bean '%s'", beanName) :
							LogMessage.format("Ignoring unresolvable metadata in bean definition '%s'", beanName));
					logger.trace(message, ex);
					// Register exception, in case the bean was accidentally unresolvable.
					onSuppressedException(ex);
				}
				catch (NoSuchBeanDefinitionException ex) {
					// Bean definition got removed while we were iterating -> ignore.
				}
			}
		}

		// Check manually registered singletons too.
		for (String beanName : this.manualSingletonNames) {
			try {
				// In case of FactoryBean, match object created by FactoryBean.
				if (isFactoryBean(beanName)) {
					if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) {
						result.add(beanName);
						// Match found for this bean: do not match FactoryBean itself anymore.
						continue;
					}
					// In case of FactoryBean, try to match FactoryBean itself next.
					beanName = FACTORY_BEAN_PREFIX + beanName;
				}
				// Match raw bean instance (might be raw FactoryBean).
				if (isTypeMatch(beanName, type)) {
					result.add(beanName);
				}
			}
			catch (NoSuchBeanDefinitionException ex) {
				// Shouldn't happen - probably a result of circular reference resolution...
				logger.trace(LogMessage.format(
						"Failed to check manually registered singleton with name '%s'", beanName), ex);
			}
		}

		return StringUtils.toStringArray(result);
	}
}

isSingleton 方法在 dbd 参数不为 null 时直接返回其是否为单例对象,否则返回 beanName 是否为单例对象名;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	private boolean isSingleton(String beanName, RootBeanDefinition mbd, @Nullable BeanDefinitionHolder dbd) {
		return (dbd != null ? mbd.isSingleton() : isSingleton(beanName));
	}
}

requiresEagerInitForType 方法用于判断 factoryBeanName 是否为工厂对象其当前还未加载为单例对象,即 factoryBeanName 参数对应对象是否需要立即加载;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	private boolean requiresEagerInitForType(@Nullable String factoryBeanName) {
		return (factoryBeanName != null && isFactoryBean(factoryBeanName) && !containsSingleton(factoryBeanName));
	}
}

3.5 getBeansOfType 方法

getBeansOfType 方法首先通过 getBeanNamesForType 方法获取 type 参数对应的对象名数组,并将其中对应对象不是 NullBean 对象时将其保存到 result 变量中并返回。

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException {
		return getBeansOfType(type, true, true);
	}

	@Override
	@SuppressWarnings("unchecked")
	public <T> Map<String, T> getBeansOfType(
			@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException {

		String[] beanNames = getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
		Map<String, T> result = new LinkedHashMap<>(beanNames.length);
		for (String beanName : beanNames) {
			try {
				Object beanInstance = getBean(beanName);
				if (!(beanInstance instanceof NullBean)) {
					result.put(beanName, (T) beanInstance);
				}
			}
			catch (BeanCreationException ex) {
				Throwable rootCause = ex.getMostSpecificCause();
				if (rootCause instanceof BeanCurrentlyInCreationException) {
					BeanCreationException bce = (BeanCreationException) rootCause;
					String exBeanName = bce.getBeanName();
					if (exBeanName != null && isCurrentlyInCreation(exBeanName)) {
						if (logger.isTraceEnabled()) {
							logger.trace("Ignoring match to currently created bean '" + exBeanName + "': " +
									ex.getMessage());
						}
						onSuppressedException(ex);
						// Ignore: indicates a circular reference when autowiring constructors.
						// We want to find matches other than the currently created bean itself.
						continue;
					}
				}
				throw ex;
			}
		}
		return result;
	}
}

3.6 getBeanNamesForAnnotation 方法

getBeanNamesForAnnotation 方法寻找 beanDefinitionNames 与 manualSingletonNames 属性中的所有非抽象且使用 annotationType 类型修饰的对象名元素并返回。

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType) {
		List<String> result = new ArrayList<>();
		for (String beanName : this.beanDefinitionNames) {
			BeanDefinition bd = this.beanDefinitionMap.get(beanName);
			if (bd != null && !bd.isAbstract() && findAnnotationOnBean(beanName, annotationType) != null) {
				result.add(beanName);
			}
		}
		for (String beanName : this.manualSingletonNames) {
			if (!result.contains(beanName) && findAnnotationOnBean(beanName, annotationType) != null) {
				result.add(beanName);
			}
		}
		return StringUtils.toStringArray(result);
	}
}

3.7 getBeansWithAnnotation 方法

getBeansWithAnnotation 方法寻找使用 annotationType 类型修饰的对象名与对象映射并返回。

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType) {
		List<String> result = new ArrayList<>();
		for (String beanName : this.beanDefinitionNames) {
			BeanDefinition bd = this.beanDefinitionMap.get(beanName);
			if (bd != null && !bd.isAbstract() && findAnnotationOnBean(beanName, annotationType) != null) {
				result.add(beanName);
			}
		}
		for (String beanName : this.manualSingletonNames) {
			if (!result.contains(beanName) && findAnnotationOnBean(beanName, annotationType) != null) {
				result.add(beanName);
			}
		}
		return StringUtils.toStringArray(result);
	}
}

3.8 findAnnotationOnBean 方法

findAnnotationOnBean 方法直接调用 findMergedAnnotationOnBean 方法获取执行定对象上的目标类型注解值;findMergedAnnotationOnBean 方法在 beanName 参数拥有对应类型时,直接利用该类型创建 MergedAnnotations 方法并通过其 get 方法获取 annotationType 参数对应的 MergedAnnotation 注解封装对象随后在其存在时直接返回该封装值;之后若当前对象工厂中包含 beanName 参数对应的对象注册表时,通过其注册表获取对应类型,并使用 MergedAnnotations 对象对其进行封装并在其使用 annotationType 类型注解修饰时直接返回;否则直接返回空注解封装对象。

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	@Nullable
	public <A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
			throws NoSuchBeanDefinitionException {

		return findMergedAnnotationOnBean(beanName, annotationType)
				.synthesize(MergedAnnotation::isPresent).orElse(null);
	}

	private <A extends Annotation> MergedAnnotation<A> findMergedAnnotationOnBean(
			String beanName, Class<A> annotationType) {

		Class<?> beanType = getType(beanName);
		if (beanType != null) {
			MergedAnnotation<A> annotation =
					MergedAnnotations.from(beanType, SearchStrategy.TYPE_HIERARCHY).get(annotationType);
			if (annotation.isPresent()) {
				return annotation;
			}
		}
		if (containsBeanDefinition(beanName)) {
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			// Check raw bean class, e.g. in case of a proxy.
			if (bd.hasBeanClass()) {
				Class<?> beanClass = bd.getBeanClass();
				if (beanClass != beanType) {
					MergedAnnotation<A> annotation =
							MergedAnnotations.from(beanClass, SearchStrategy.TYPE_HIERARCHY).get(annotationType);
					if (annotation.isPresent()) {
						return annotation;
					}
				}
			}
			// Check annotations declared on factory method, if any.
			Method factoryMethod = bd.getResolvedFactoryMethod();
			if (factoryMethod != null) {
				MergedAnnotation<A> annotation =
						MergedAnnotations.from(factoryMethod, SearchStrategy.TYPE_HIERARCHY).get(annotationType);
				if (annotation.isPresent()) {
					return annotation;
				}
			}
		}
		return MergedAnnotation.missing();
	}
}

4 ConfigurableListableBeanFactory 接口方法实现

4.1 registerResolvableDependency 方法

registerResolvableDependency 方法首先对 dependencyType 参数进行非空验证,随后在 autowiredValue 参数不为 null 时,验证其是否为 ObjectFactory 对象或 dependencyType 类型对象并在通过验证后将 dependencyType 与 autowiredValue 映射保存到 resolvableDependencies 属性中;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public void registerResolvableDependency(Class<?> dependencyType, @Nullable Object autowiredValue) {
		Assert.notNull(dependencyType, "Dependency type must not be null");
		if (autowiredValue != null) {
			if (!(autowiredValue instanceof ObjectFactory || dependencyType.isInstance(autowiredValue))) {
				throw new IllegalArgumentException("Value [" + autowiredValue +
						"] does not implement specified dependency type [" + dependencyType.getName() + "]");
			}
			this.resolvableDependencies.put(dependencyType, autowiredValue);
		}
	}
}

4.2 isAutowireCandidate 方法

isAutowireCandidate 方法在当前对象工厂中拥有 beanName 参数对应对象注册表或单例对象时,直接执行四参数 isAutowireCandidate 方法并返回;在其拥有 DefaultListableBeanFactory 或 ConfigurableListableBeanFactory 类型的父对象工厂时直接递归调用对应的 isAutowireCandidate 方法并返回,否则直接返回 true;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor)
			throws NoSuchBeanDefinitionException {

		return isAutowireCandidate(beanName, descriptor, getAutowireCandidateResolver());
	}

	protected boolean isAutowireCandidate(
			String beanName, DependencyDescriptor descriptor, AutowireCandidateResolver resolver)
			throws NoSuchBeanDefinitionException {

		String bdName = BeanFactoryUtils.transformedBeanName(beanName);
		if (containsBeanDefinition(bdName)) {
			return isAutowireCandidate(beanName, getMergedLocalBeanDefinition(bdName), descriptor, resolver);
		}
		else if (containsSingleton(beanName)) {
			return isAutowireCandidate(beanName, new RootBeanDefinition(getType(beanName)), descriptor, resolver);
		}

		BeanFactory parent = getParentBeanFactory();
		if (parent instanceof DefaultListableBeanFactory) {
			// No bean definition found in this factory -> delegate to parent.
			return ((DefaultListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor, resolver);
		}
		else if (parent instanceof ConfigurableListableBeanFactory) {
			// If no DefaultListableBeanFactory, can't pass the resolver along.
			return ((ConfigurableListableBeanFactory) parent).isAutowireCandidate(beanName, descriptor);
		}
		else {
			return true;
		}
	}
}

四参数 isAutowireCandidate 方法在 mbd 参数的 isFactoryMethodUnique 属性为 true 且其 factoryMethodToIntrospect 属性不为空时对 factoryMethodToIntrospect 属性进行赋值;之后使用 mbd、beabName 参数及其所有别名创建 BeanDefinitionHolder 对象并为 holder 进行赋值,其中若 beanName 参数就是对象的原始名时会将 beanName 参数与 holder 变量值缓存到 mergedBeanDefinitionHolders 属性中;最后使用 resolver 参数的 isAutowireCandidate 判断 holder 变量是否为 descriptor 参数的候选项。

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	protected boolean isAutowireCandidate(String beanName, RootBeanDefinition mbd,
			DependencyDescriptor descriptor, AutowireCandidateResolver resolver) {

		String bdName = BeanFactoryUtils.transformedBeanName(beanName);
		resolveBeanClass(mbd, bdName);
		if (mbd.isFactoryMethodUnique && mbd.factoryMethodToIntrospect == null) {
			new ConstructorResolver(this).resolveFactoryMethodIfPossible(mbd);
		}
		BeanDefinitionHolder holder = (beanName.equals(bdName) ?
				this.mergedBeanDefinitionHolders.computeIfAbsent(beanName,
						key -> new BeanDefinitionHolder(mbd, beanName, getAliases(bdName))) :
				new BeanDefinitionHolder(mbd, beanName, getAliases(bdName)));
		return resolver.isAutowireCandidate(holder, descriptor);
	}
}

4.3 getBeanDefinition 方法

getBeanDefinition 方法若 beanDefinitionMap 属性中没有 beanName 参数对应注册表时抛出 NoSuchBeanDefinitionException 异常,否则返回对应 BeanDefinition 对象值;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException {
		BeanDefinition bd = this.beanDefinitionMap.get(beanName);
		if (bd == null) {
			if (logger.isTraceEnabled()) {
				logger.trace("No bean named '" + beanName + "' found in " + this);
			}
			throw new NoSuchBeanDefinitionException(beanName);
		}
		return bd;
	}
}

4.4 getBeanNamesIterator 方法

getBeanNamesIterator 方法将 beanDefinitionNames 与 manualSingletonNames 属性的迭代器合成为一个混合迭代器并返回;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public Iterator<String> getBeanNamesIterator() {
		CompositeIterator<String> iterator = new CompositeIterator<>();
		iterator.add(this.beanDefinitionNames.iterator());
		iterator.add(this.manualSingletonNames.iterator());
		return iterator;
	}
}

4.5 clearMergedBeanDefinition 方法

clearMergedBeanDefinition 方法为父类的 clearMergedBeanDefinition 方法扩展了移除 mergedBeanDefinitionHolders 属性对应值的功能;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	protected void clearMergedBeanDefinition(String beanName) {
		super.clearMergedBeanDefinition(beanName);
		this.mergedBeanDefinitionHolders.remove(beanName);
	}
}

4.6 freezeConfiguration 方法

freezeConfiguration 方法在将 configurationFrozen 属性置为 true 的同时将 beanDefinitionNames 属性转换为字符串数组保存到 frozenBeanDefinitionNames 属性中;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public void freezeConfiguration() {
		this.configurationFrozen = true;
		this.frozenBeanDefinitionNames = StringUtils.toStringArray(this.beanDefinitionNames);
	}
}

4.7 isConfigurationFrozen 方法

isConfigurationFrozen 方法返回 configurationFrozen 属性值;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public boolean isConfigurationFrozen() {
		return this.configurationFrozen;
	}
}

4.8 isBeanEligibleForMetadataCaching 方法

isConfigurationFrozen 方法用于判断指定对象是否可缓存元数据,其在 configurationFrozen 为 true,即当前配置已冻结,所有的对象元数据都可缓存,否则返回父类的对应方法值。

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	protected boolean isBeanEligibleForMetadataCaching(String beanName) {
		return (this.configurationFrozen || super.isBeanEligibleForMetadataCaching(beanName));
	}
}

4.9 preInstantiateSingletons 方法

preInstantiateSingletons 方法用于预初始化所有非延迟初始化对象,其首先通过 getBean 方法对 beanDefinitionNames 属性中所有单例非延迟加载的非抽象对象进行加载;在加载完成后,在对应单例对象为 SmartInitializingSingleton 类型数据时对其执行 afterSingletonsInstantiated 方法进行单例对象初始化后处理。

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public void preInstantiateSingletons() throws BeansException {
		if (logger.isTraceEnabled()) {
			logger.trace("Pre-instantiating singletons in " + this);
		}

		// Iterate over a copy to allow for init methods which in turn register new bean definitions.
		// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
		List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

		// Trigger initialization of all non-lazy singleton beans...
		for (String beanName : beanNames) {
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
				if (isFactoryBean(beanName)) {
					Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
					if (bean instanceof FactoryBean) {
						FactoryBean<?> factory = (FactoryBean<?>) bean;
						boolean isEagerInit;
						if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
							isEagerInit = AccessController.doPrivileged(
									(PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
									getAccessControlContext());
						}
						else {
							isEagerInit = (factory instanceof SmartFactoryBean &&
									((SmartFactoryBean<?>) factory).isEagerInit());
						}
						if (isEagerInit) {
							getBean(beanName);
						}
					}
				}
				else {
					getBean(beanName);
				}
			}
		}

		// Trigger post-initialization callback for all applicable beans...
		for (String beanName : beanNames) {
			Object singletonInstance = getSingleton(beanName);
			if (singletonInstance instanceof SmartInitializingSingleton) {
				SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
				if (System.getSecurityManager() != null) {
					AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
						smartSingleton.afterSingletonsInstantiated();
						return null;
					}, getAccessControlContext());
				}
				else {
					smartSingleton.afterSingletonsInstantiated();
				}
			}
		}
	}
}

5 BeanDefinitionRegistry 接口方法实现

5.1 registerBeanDefinition 方法

registerBeanDefinition 方法首先分别对 beanName 与 beanDefinition 参数进行非空验证,同时在 beanDefinition 参数为 AbstractBeanDefinition 对象时执行其 validate 方法进行进一步验证;之后在当前对象工厂已存在同名注册表对象时,首先判断其是否允许同名注册表的重写,不允许直接抛出异常,允许时将 beanName 与 beanDefinition 参数映射注册到 beanDefinitionMap 属性中;在当前对象工厂不存在同名注册表时,则会在将 beanName 与 beanDefinition 参数映射注册到 beanDefinitionMap 属性中的同时,将 beanName 参数保存到 beanDefinitionNames 属性中并调用 removeManualSingletonName 方法尝试从 manualSingletonNames 属性中移除该属性值,最后将 frozenBeanDefinitionNames 属性置为 null;最后若注册的是同名注册表或当前已有同步单例对象时,会调用 resetBeanDefinition 方法重置 beanName 参数对应的注册表信息;否则在当前配置已冻结时则会调用 clearByTypeCache 方法清空类型相关缓存。

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
			throws BeanDefinitionStoreException {

		Assert.hasText(beanName, "Bean name must not be empty");
		Assert.notNull(beanDefinition, "BeanDefinition must not be null");

		if (beanDefinition instanceof AbstractBeanDefinition) {
			try {
				((AbstractBeanDefinition) beanDefinition).validate();
			}
			catch (BeanDefinitionValidationException ex) {
				throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
						"Validation of bean definition failed", ex);
			}
		}

		BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
		if (existingDefinition != null) {
			if (!isAllowBeanDefinitionOverriding()) {
				throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
			}
			else if (existingDefinition.getRole() < beanDefinition.getRole()) {
				// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
				if (logger.isInfoEnabled()) {
					logger.info("Overriding user-defined bean definition for bean '" + beanName +
							"' with a framework-generated bean definition: replacing [" +
							existingDefinition + "] with [" + beanDefinition + "]");
				}
			}
			else if (!beanDefinition.equals(existingDefinition)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Overriding bean definition for bean '" + beanName +
							"' with a different definition: replacing [" + existingDefinition +
							"] with [" + beanDefinition + "]");
				}
			}
			else {
				if (logger.isTraceEnabled()) {
					logger.trace("Overriding bean definition for bean '" + beanName +
							"' with an equivalent definition: replacing [" + existingDefinition +
							"] with [" + beanDefinition + "]");
				}
			}
			this.beanDefinitionMap.put(beanName, beanDefinition);
		}
		else {
			if (hasBeanCreationStarted()) {
				// Cannot modify startup-time collection elements anymore (for stable iteration)
				synchronized (this.beanDefinitionMap) {
					this.beanDefinitionMap.put(beanName, beanDefinition);
					List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
					updatedDefinitions.addAll(this.beanDefinitionNames);
					updatedDefinitions.add(beanName);
					this.beanDefinitionNames = updatedDefinitions;
					removeManualSingletonName(beanName);
				}
			}
			else {
				// Still in startup registration phase
				this.beanDefinitionMap.put(beanName, beanDefinition);
				this.beanDefinitionNames.add(beanName);
				removeManualSingletonName(beanName);
			}
			this.frozenBeanDefinitionNames = null;
		}

		if (existingDefinition != null || containsSingleton(beanName)) {
			resetBeanDefinition(beanName);
		}
		else if (isConfigurationFrozen()) {
			clearByTypeCache();
		}
	}

	private void removeManualSingletonName(String beanName) {
		updateManualSingletonNames(set -> set.remove(beanName), set -> set.contains(beanName));
	}
}

5.2 removeBeanDefinition 方法

removeBeanDefinition 方法在通过对 beanName 参数的非空验证后,尝试从 beanDefinitionMap 属性中移除对应的注册表缓存,若对应注册表信息为 null 则直接抛出异常;之后将会从 beanDefinitionNames 属性中移除该参数值并将 frozenBeanDefinitionNames 属性置为 null,最后调用 resetBeanDefinition 方法重置对应注册表对象值。

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException {
		Assert.hasText(beanName, "'beanName' must not be empty");

		BeanDefinition bd = this.beanDefinitionMap.remove(beanName);
		if (bd == null) {
			if (logger.isTraceEnabled()) {
				logger.trace("No bean named '" + beanName + "' found in " + this);
			}
			throw new NoSuchBeanDefinitionException(beanName);
		}

		if (hasBeanCreationStarted()) {
			// Cannot modify startup-time collection elements anymore (for stable iteration)
			synchronized (this.beanDefinitionMap) {
				List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames);
				updatedDefinitions.remove(beanName);
				this.beanDefinitionNames = updatedDefinitions;
			}
		}
		else {
			// Still in startup registration phase
			this.beanDefinitionNames.remove(beanName);
		}
		this.frozenBeanDefinitionNames = null;

		resetBeanDefinition(beanName);
	}
}

5.3 resetBeanDefinition 方法

resetBeanDefinition 方法首先调用 clearMergedBeanDefinition 方法移除 beanName 参数对应综合注册表同时调用 destroySingleton 方法销毁对应的单例对象;随后执行执行器列表中的 MergedBeanDefinitionPostProcessor 元素的 resetBeanDefinition 方法重置对象注册表;最后递归对父注册表对象执行 resetBeanDefinition 方法对其进行重置。

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	protected void resetBeanDefinition(String beanName) {
		// Remove the merged bean definition for the given bean, if already created.
		clearMergedBeanDefinition(beanName);

		// Remove corresponding bean from singleton cache, if any. Shouldn't usually
		// be necessary, rather just meant for overriding a context's default beans
		// (e.g. the default StaticMessageSource in a StaticApplicationContext).
		destroySingleton(beanName);

		// Notify all post-processors that the specified bean definition has been reset.
		for (BeanPostProcessor processor : getBeanPostProcessors()) {
			if (processor instanceof MergedBeanDefinitionPostProcessor) {
				((MergedBeanDefinitionPostProcessor) processor).resetBeanDefinition(beanName);
			}
		}

		// Reset all bean definitions that have the given bean as parent (recursively).
		for (String bdName : this.beanDefinitionNames) {
			if (!beanName.equals(bdName)) {
				BeanDefinition bd = this.beanDefinitionMap.get(bdName);
				// Ensure bd is non-null due to potential concurrent modification of beanDefinitionMap.
				if (bd != null && beanName.equals(bd.getParentName())) {
					resetBeanDefinition(bdName);
				}
			}
		}
	}
}

5.4 allowAliasOverriding 方法

allowAliasOverriding 方法直接执行 isAllowBeanDefinitionOverriding 方法返回 allowBeanDefinitionOverriding 属性值。

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	protected boolean allowAliasOverriding() {
		return isAllowBeanDefinitionOverriding();
	}
}

5.5 registerSingleton 方法

registerSingleton 方法在执行父对象的 registerSingleton 方法向工厂中注册对象注册表的同时,在 beanDefinitionMap 属性中不包含 beanName 参数将其保存到 manualSingletonNames 属性中,最后调用 clearByTypeCache 方法清空类型相关缓存。

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
		super.registerSingleton(beanName, singletonObject);
		updateManualSingletonNames(set -> set.add(beanName), set -> !this.beanDefinitionMap.containsKey(beanName));
		clearByTypeCache();
	}
}

5.6 destroySingletons 方法

destroySingletons 方法在执行父类的 destroySingletons 方法销毁所有单例对象的同时清空 manualSingletonNames 属性并调用 clearByTypeCache 方法清空类型相关缓存。

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public void destroySingletons() {
		super.destroySingletons();
		updateManualSingletonNames(Set::clear, set -> !set.isEmpty());
		clearByTypeCache();
	}
}

5.7 destroySingleton 方法

destroySingleton 方法在执行父类的 destroySingleton 方法销毁对应单例对象的同时移除 manualSingletonNames 属性指定值并调用 clearByTypeCache 方法清空类型相关缓存。

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public void destroySingleton(String beanName) {
		super.destroySingleton(beanName);
		removeManualSingletonName(beanName);
		clearByTypeCache();
	}
}

5.8 updateManualSingletonNames 方法

updateManualSingletonNames 方法在 manualSingletonNames 属性满足 condition 条件时对其执行 action 定义的方法。

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	private void updateManualSingletonNames(Consumer<Set<String>> action, Predicate<Set<String>> condition) {
		if (hasBeanCreationStarted()) {
			// Cannot modify startup-time collection elements anymore (for stable iteration)
			synchronized (this.beanDefinitionMap) {
				if (condition.test(this.manualSingletonNames)) {
					Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
					action.accept(updatedSingletons);
					this.manualSingletonNames = updatedSingletons;
				}
			}
		}
		else {
			// Still in startup registration phase
			if (condition.test(this.manualSingletonNames)) {
				action.accept(this.manualSingletonNames);
			}
		}
	}
}

6 依赖解析方法

6.1 resolveNamedBean 方法

向外提供的 resolveNamedBean 方法在调用当前与父对象工厂的 resolveNamedBean 方法都为获取到对应的 NamedBeanHolder 对象时直接抛出 NoSuchBeanDefinitionException 异常;私有 resolveNamedBean 方法首先在拥有多于一个 requiredType 类型的对应注册表时,过滤其中不能作为自动注入候选项的本地注册表对象值;若过滤后只有一个满足请求,则直接使用该元素创建 NamedBeanHolder 对象并返回,否则继续过滤其中的非空对象并调用 determinePrimaryCandidate 方法确定其中的 Primary 候选值,若未获取到则调用 determineHighestPriorityCandidate 方法确认高优先级候选值,获取到时获取对应对象值,注意在其为空时,会使用 getBean 方法创建对象并使用 NamedBeanHolder 对象进行封装并返回;否则返回 null;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	public <T> NamedBeanHolder<T> resolveNamedBean(Class<T> requiredType) throws BeansException {
		Assert.notNull(requiredType, "Required type must not be null");
		NamedBeanHolder<T> namedBean = resolveNamedBean(ResolvableType.forRawClass(requiredType), null, false);
		if (namedBean != null) {
			return namedBean;
		}
		BeanFactory parent = getParentBeanFactory();
		if (parent instanceof AutowireCapableBeanFactory) {
			return ((AutowireCapableBeanFactory) parent).resolveNamedBean(requiredType);
		}
		throw new NoSuchBeanDefinitionException(requiredType);
	}

	@SuppressWarnings("unchecked")
	@Nullable
	private <T> NamedBeanHolder<T> resolveNamedBean(
			ResolvableType requiredType, @Nullable Object[] args, boolean nonUniqueAsNull) throws BeansException {

		Assert.notNull(requiredType, "Required type must not be null");
		String[] candidateNames = getBeanNamesForType(requiredType);

		if (candidateNames.length > 1) {
			List<String> autowireCandidates = new ArrayList<>(candidateNames.length);
			for (String beanName : candidateNames) {
				if (!containsBeanDefinition(beanName) || getBeanDefinition(beanName).isAutowireCandidate()) {
					autowireCandidates.add(beanName);
				}
			}
			if (!autowireCandidates.isEmpty()) {
				candidateNames = StringUtils.toStringArray(autowireCandidates);
			}
		}

		if (candidateNames.length == 1) {
			String beanName = candidateNames[0];
			return new NamedBeanHolder<>(beanName, (T) getBean(beanName, requiredType.toClass(), args));
		}
		else if (candidateNames.length > 1) {
			Map<String, Object> candidates = new LinkedHashMap<>(candidateNames.length);
			for (String beanName : candidateNames) {
				if (containsSingleton(beanName) && args == null) {
					Object beanInstance = getBean(beanName);
					candidates.put(beanName, (beanInstance instanceof NullBean ? null : beanInstance));
				}
				else {
					candidates.put(beanName, getType(beanName));
				}
			}
			String candidateName = determinePrimaryCandidate(candidates, requiredType.toClass());
			if (candidateName == null) {
				candidateName = determineHighestPriorityCandidate(candidates, requiredType.toClass());
			}
			if (candidateName != null) {
				Object beanInstance = candidates.get(candidateName);
				if (beanInstance == null || beanInstance instanceof Class) {
					beanInstance = getBean(candidateName, requiredType.toClass(), args);
				}
				return new NamedBeanHolder<>(candidateName, (T) beanInstance);
			}
			if (!nonUniqueAsNull) {
				throw new NoUniqueBeanDefinitionException(requiredType, candidates.keySet());
			}
		}

		return null;
	}
}

6.2 resolveDependency 方法

resolveDependency 方法首先使用 parameterNameDiscoverer 属性初始化 descriptor 参数的参数名查询器;在 descriptor 参数的类型为 Optional 时,使用 createOptionalDependency 方法创建依赖对象并返回,在其为 ObjectFactory 或 ObjectProvider 对象时,创建 DependencyObjectProvider 对象并返回,在其为 javaxInjectProviderClass 属性定义的类型时使用 Jsr330Factory 对象工厂创建对应的依赖对象并返回,否则通过 autowireCandidateResolver 属性获取依赖对象,未获取到则尝试 doResolveDependency 方法解析依赖并返回解析值。

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Override
	@Nullable
	public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

		descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
		if (Optional.class == descriptor.getDependencyType()) {
			return createOptionalDependency(descriptor, requestingBeanName);
		}
		else if (ObjectFactory.class == descriptor.getDependencyType() ||
				ObjectProvider.class == descriptor.getDependencyType()) {
			return new DependencyObjectProvider(descriptor, requestingBeanName);
		}
		else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
			return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
		}
		else {
			Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
					descriptor, requestingBeanName);
			if (result == null) {
				result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
			}
			return result;
		}
	}
}

6.3 doResolveDependency 方法

doResolveDependency 方法首先尝试从 descriptor 的 resolveShortcut 方法获取当前快照,若获取到直接返回;随后尝试从 autowireCandidateResolver 属性中获取推荐值,在其不为空时,首先调用 resolveEmbeddedValue 方法解析该值并调用 evaluateBeanDefinitionString 方法解析字符值,最后调用 typeConverter 的 convertIfNecessary 方法转换对象并返回;在推荐值为空时,尝试使用 resolveMultipleBeans 方法解析集合类型依赖,成功解析后直接返回该值;之后通过 findAutowireCandidates 方法获取候选对象列表,在其为空时,且非必填时直接返回 null,否则抛出异常;在候选值的数量大于 1 时,使用 determineAutowireCandidate 确定依赖对象名,在其不为 null 时直接获取对应值,否则在其为必须或不为集合类型,返回 resolveNotUnique 方法结果值;只有一个候选项时,在 autowiredBeanNames 参数不为空时,将自动注入名保存到其中,最后返回该对象值;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Nullable
	public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

		InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
		try {
			Object shortcut = descriptor.resolveShortcut(this);
			if (shortcut != null) {
				return shortcut;
			}

			Class<?> type = descriptor.getDependencyType();
			Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
			if (value != null) {
				if (value instanceof String) {
					String strVal = resolveEmbeddedValue((String) value);
					BeanDefinition bd = (beanName != null && containsBean(beanName) ?
							getMergedBeanDefinition(beanName) : null);
					value = evaluateBeanDefinitionString(strVal, bd);
				}
				TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
				try {
					return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());
				}
				catch (UnsupportedOperationException ex) {
					// A custom TypeConverter which does not support TypeDescriptor resolution...
					return (descriptor.getField() != null ?
							converter.convertIfNecessary(value, type, descriptor.getField()) :
							converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
				}
			}

			Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
			if (multipleBeans != null) {
				return multipleBeans;
			}

			Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
			if (matchingBeans.isEmpty()) {
				if (isRequired(descriptor)) {
					raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
				}
				return null;
			}

			String autowiredBeanName;
			Object instanceCandidate;

			if (matchingBeans.size() > 1) {
				autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
				if (autowiredBeanName == null) {
					if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
						return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
					}
					else {
						// In case of an optional Collection/Map, silently ignore a non-unique case:
						// possibly it was meant to be an empty collection of multiple regular beans
						// (before 4.3 in particular when we didn't even look for collection beans).
						return null;
					}
				}
				instanceCandidate = matchingBeans.get(autowiredBeanName);
			}
			else {
				// We have exactly one match.
				Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
				autowiredBeanName = entry.getKey();
				instanceCandidate = entry.getValue();
			}

			if (autowiredBeanNames != null) {
				autowiredBeanNames.add(autowiredBeanName);
			}
			if (instanceCandidate instanceof Class) {
				instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
			}
			Object result = instanceCandidate;
			if (result instanceof NullBean) {
				if (isRequired(descriptor)) {
					raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
				}
				result = null;
			}
			if (!ClassUtils.isAssignableValue(type, result)) {
				throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass());
			}
			return result;
		}
		finally {
			ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
		}
	}
}

resolveMultipleBeans 方法用于解析集合类型依赖,在 descriptor 参数为 StreamDependencyDescriptor 对象,即其为流式依赖时,其首先通过 findAutowireCandidates 方法获取符合依赖的对象名对象映射并在 autowiredBeanNames 参数不为空时,将其中所有对象名保存到该参数中;随后将其中的非空对象元素封装为对象流,并在需要进行排序时对其进行排序,然后返回该流对象;

在依赖对象为数组时,首先获取其元素类型并为 componentType 变量赋值,在该类型为 null 时直接返回 null;随后通过 findAutowireCandidates 方法获取符合依赖限制的元素类型对象的名称对象值映射,在其为空时也直接返回 null;之后也会在 autowiredBeanNames 参数不为空时,将其中所有对象名保存到该参数中;之后使用 converter 类型转换器将获取到的所有对象值转换为结果对象,并在需要进行排序时,调用 adaptDependencyComparator 方法获取对应比较器进行排序,最后返回该值;

在依赖对象类型为继承了 Collection 的接口时,首先尝试获取器泛型值,在其没有泛型值时直接返回 null;否则也会通过 findAutowireCandidates 方法获取符合依赖限制的元素类型对象的名称对象值映射,若其为空则直接返回 null;随后也会在 autowiredBeanNames 参数不为空时,将其中所有对象名保存到该参数中;之后使用 converter 类型转换器将获取到的所有对象值转换为结果对象,并在需要进行排序时,调用 adaptDependencyComparator 方法获取对应比较器进行排序,最后返回该值;

在依赖对象为 Map 时,在其 key 不为 String 或其没有 value 泛型时直接返回 null;否则也会通过 findAutowireCandidates 方法获取符合依赖限制的元素类型对象的名称对象值映射,若其为空则直接返回 null;随后也会在 autowiredBeanNames 参数不为空时,将其中所有对象名保存到该参数中,随后直接返回 findAutowireCandidates 方法的执行结果;

在其他情况下直接返回 null;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Nullable
	private Object resolveMultipleBeans(DependencyDescriptor descriptor, @Nullable String beanName,
			@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) {

		Class<?> type = descriptor.getDependencyType();

		if (descriptor instanceof StreamDependencyDescriptor) {
			Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
			if (autowiredBeanNames != null) {
				autowiredBeanNames.addAll(matchingBeans.keySet());
			}
			Stream<Object> stream = matchingBeans.keySet().stream()
					.map(name -> descriptor.resolveCandidate(name, type, this))
					.filter(bean -> !(bean instanceof NullBean));
			if (((StreamDependencyDescriptor) descriptor).isOrdered()) {
				stream = stream.sorted(adaptOrderComparator(matchingBeans));
			}
			return stream;
		}
		else if (type.isArray()) {
			Class<?> componentType = type.getComponentType();
			ResolvableType resolvableType = descriptor.getResolvableType();
			Class<?> resolvedArrayType = resolvableType.resolve(type);
			if (resolvedArrayType != type) {
				componentType = resolvableType.getComponentType().resolve();
			}
			if (componentType == null) {
				return null;
			}
			Map<String, Object> matchingBeans = findAutowireCandidates(beanName, componentType,
					new MultiElementDescriptor(descriptor));
			if (matchingBeans.isEmpty()) {
				return null;
			}
			if (autowiredBeanNames != null) {
				autowiredBeanNames.addAll(matchingBeans.keySet());
			}
			TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
			Object result = converter.convertIfNecessary(matchingBeans.values(), resolvedArrayType);
			if (result instanceof Object[]) {
				Comparator<Object> comparator = adaptDependencyComparator(matchingBeans);
				if (comparator != null) {
					Arrays.sort((Object[]) result, comparator);
				}
			}
			return result;
		}
		else if (Collection.class.isAssignableFrom(type) && type.isInterface()) {
			Class<?> elementType = descriptor.getResolvableType().asCollection().resolveGeneric();
			if (elementType == null) {
				return null;
			}
			Map<String, Object> matchingBeans = findAutowireCandidates(beanName, elementType,
					new MultiElementDescriptor(descriptor));
			if (matchingBeans.isEmpty()) {
				return null;
			}
			if (autowiredBeanNames != null) {
				autowiredBeanNames.addAll(matchingBeans.keySet());
			}
			TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
			Object result = converter.convertIfNecessary(matchingBeans.values(), type);
			if (result instanceof List) {
				if (((List<?>) result).size() > 1) {
					Comparator<Object> comparator = adaptDependencyComparator(matchingBeans);
					if (comparator != null) {
						((List<?>) result).sort(comparator);
					}
				}
			}
			return result;
		}
		else if (Map.class == type) {
			ResolvableType mapType = descriptor.getResolvableType().asMap();
			Class<?> keyType = mapType.resolveGeneric(0);
			if (String.class != keyType) {
				return null;
			}
			Class<?> valueType = mapType.resolveGeneric(1);
			if (valueType == null) {
				return null;
			}
			Map<String, Object> matchingBeans = findAutowireCandidates(beanName, valueType,
					new MultiElementDescriptor(descriptor));
			if (matchingBeans.isEmpty()) {
				return null;
			}
			if (autowiredBeanNames != null) {
				autowiredBeanNames.addAll(matchingBeans.keySet());
			}
			return matchingBeans;
		}
		else {
			return null;
		}
	}
}

isRequired 方法用于判断指定依赖是否为必须的;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	private boolean isRequired(DependencyDescriptor descriptor) {
		return getAutowireCandidateResolver().isRequired(descriptor);
	}
}

indicatesMultipleBeans 方法用于判断指定类型是否为集合;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	private boolean indicatesMultipleBeans(Class<?> type) {
		return (type.isArray() || (type.isInterface() &&
				(Collection.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type))));
	}
}

adaptDependencyComparator 方法在 dependencyComparator 属性为 OrderComparator 对象时,调用其 withSourceProvider 方法获取对应比较器并返回,否则直接返回该属性值;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Nullable
	private Comparator<Object> adaptDependencyComparator(Map<String, ?> matchingBeans) {
		Comparator<Object> comparator = getDependencyComparator();
		if (comparator instanceof OrderComparator) {
			return ((OrderComparator) comparator).withSourceProvider(
					createFactoryAwareOrderSourceProvider(matchingBeans));
		}
		else {
			return comparator;
		}
	}
}

adaptOrderComparator 方法在 dependencyComparator 属性为 OrderComparator 对象时,调用其 withSourceProvider 方法获取对应比较器并返回,否则使用 OrderComparator 类中的单例的 withSourceProvider 方法获取对应比较器并返回;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	private Comparator<Object> adaptOrderComparator(Map<String, ?> matchingBeans) {
		Comparator<Object> dependencyComparator = getDependencyComparator();
		OrderComparator comparator = (dependencyComparator instanceof OrderComparator ?
				(OrderComparator) dependencyComparator : OrderComparator.INSTANCE);
		return comparator.withSourceProvider(createFactoryAwareOrderSourceProvider(matchingBeans));
	}
}

createFactoryAwareOrderSourceProvider 方法将 beans 参数交换其的 key 与 value 值并使用转换后的对象创建 FactoryAwareOrderSourceProvider 对象并返回;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	private OrderComparator.OrderSourceProvider createFactoryAwareOrderSourceProvider(Map<String, ?> beans) {
		IdentityHashMap<Object, String> instancesToBeanNames = new IdentityHashMap<>();
		beans.forEach((beanName, instance) -> instancesToBeanNames.put(instance, beanName));
		return new FactoryAwareOrderSourceProvider(instancesToBeanNames);
	}
}

findAutowireCandidates 方法首先获取当前对象工厂中所有指定类型对象名,同时将 resolvableDependencies 属性中 requiredType 类型对象的象名 id 与该对象保存到 result 局部变量之中;随后将指定对象名数组中的非当前对象且满足 descriptor 参数的元素调用 addCandidateEntry 方法保存到 result 变量之中;若经过上述过程,result 变量中已拥有元素直接返回该变量,否则使用 descriptor 参数的回调依赖对象判断 candidateNames 是有存在匹配元素,若存在将其保存到 result 中返回;若还未匹配上且不为集合依赖则会尝试查找从同一工厂对象创建的候选项返回;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	protected Map<String, Object> findAutowireCandidates(
			@Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {

		String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
				this, requiredType, true, descriptor.isEager());
		Map<String, Object> result = new LinkedHashMap<>(candidateNames.length);
		for (Map.Entry<Class<?>, Object> classObjectEntry : this.resolvableDependencies.entrySet()) {
			Class<?> autowiringType = classObjectEntry.getKey();
			if (autowiringType.isAssignableFrom(requiredType)) {
				Object autowiringValue = classObjectEntry.getValue();
				autowiringValue = AutowireUtils.resolveAutowiringValue(autowiringValue, requiredType);
				if (requiredType.isInstance(autowiringValue)) {
					result.put(ObjectUtils.identityToString(autowiringValue), autowiringValue);
					break;
				}
			}
		}
		for (String candidate : candidateNames) {
			if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) {
				addCandidateEntry(result, candidate, descriptor, requiredType);
			}
		}
		if (result.isEmpty()) {
			boolean multiple = indicatesMultipleBeans(requiredType);
			// Consider fallback matches if the first pass failed to find anything...
			DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch();
			for (String candidate : candidateNames) {
				if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, fallbackDescriptor) &&
						(!multiple || getAutowireCandidateResolver().hasQualifier(descriptor))) {
					addCandidateEntry(result, candidate, descriptor, requiredType);
				}
			}
			if (result.isEmpty() && !multiple) {
				// Consider self references as a final pass...
				// but in the case of a dependency collection, not the very same bean itself.
				for (String candidate : candidateNames) {
					if (isSelfReference(beanName, candidate) &&
							(!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) &&
							isAutowireCandidate(candidate, fallbackDescriptor)) {
						addCandidateEntry(result, candidate, descriptor, requiredType);
					}
				}
			}
		}
		return result;
	}
}

addCandidateEntry 方法在 descriptor 参数为 MultiElementDescriptor 对象时,在当前对象工厂中拥有 candidateName 参数对应对象时将其对象名与该对象映射保存到 candidates 参数中,在当前工厂拥有 candidateName 对应的单例对象,也获取对应单例对象并保存到 candidates 参数中,否则直接将 candidateName 参数与 getType 方法获取的 candidateName 对应的类型结果映射保存到 candidates 参数中;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	private void addCandidateEntry(Map<String, Object> candidates, String candidateName,
			DependencyDescriptor descriptor, Class<?> requiredType) {

		if (descriptor instanceof MultiElementDescriptor) {
			Object beanInstance = descriptor.resolveCandidate(candidateName, requiredType, this);
			if (!(beanInstance instanceof NullBean)) {
				candidates.put(candidateName, beanInstance);
			}
		}
		else if (containsSingleton(candidateName) || (descriptor instanceof StreamDependencyDescriptor &&
				((StreamDependencyDescriptor) descriptor).isOrdered())) {
			Object beanInstance = descriptor.resolveCandidate(candidateName, requiredType, this);
			candidates.put(candidateName, (beanInstance instanceof NullBean ? null : beanInstance));
		}
		else {
			candidates.put(candidateName, getType(candidateName));
		}
	}
}

determineAutowireCandidate 方法用于从 candidates 参数中获取最匹配的候选项;其首先通过 determinePrimaryCandidate 方法确定主要候选,在通过 determineHighestPriorityCandidate 方法获取高优先级候选项,否则返回 candidates 属性中已解析对象或名字能匹配的对象,否则直接返回 null;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Nullable
	protected String determineAutowireCandidate(Map<String, Object> candidates, DependencyDescriptor descriptor) {
		Class<?> requiredType = descriptor.getDependencyType();
		String primaryCandidate = determinePrimaryCandidate(candidates, requiredType);
		if (primaryCandidate != null) {
			return primaryCandidate;
		}
		String priorityCandidate = determineHighestPriorityCandidate(candidates, requiredType);
		if (priorityCandidate != null) {
			return priorityCandidate;
		}
		// Fallback
		for (Map.Entry<String, Object> entry : candidates.entrySet()) {
			String candidateName = entry.getKey();
			Object beanInstance = entry.getValue();
			if ((beanInstance != null && this.resolvableDependencies.containsValue(beanInstance)) ||
					matchesBeanName(candidateName, descriptor.getDependencyName())) {
				return candidateName;
			}
		}
		return null;
	}
}

determinePrimaryCandidate 方法用于获取候选对象用使用 Primary 注解修饰的对象并返回,注意所有依赖中只能有一个,多于一个时会抛出异常;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Nullable
	protected String determinePrimaryCandidate(Map<String, Object> candidates, Class<?> requiredType) {
		String primaryBeanName = null;
		for (Map.Entry<String, Object> entry : candidates.entrySet()) {
			String candidateBeanName = entry.getKey();
			Object beanInstance = entry.getValue();
			if (isPrimary(candidateBeanName, beanInstance)) {
				if (primaryBeanName != null) {
					boolean candidateLocal = containsBeanDefinition(candidateBeanName);
					boolean primaryLocal = containsBeanDefinition(primaryBeanName);
					if (candidateLocal && primaryLocal) {
						throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(),
								"more than one 'primary' bean found among candidates: " + candidates.keySet());
					}
					else if (candidateLocal) {
						primaryBeanName = candidateBeanName;
					}
				}
				else {
					primaryBeanName = candidateBeanName;
				}
			}
		}
		return primaryBeanName;
	}
}

determineHighestPriorityCandidate 方法用于获取候选对象最高优先级(其类上 Order 注解的值最大)对象并返回,值得注意的是,不能存在两个相同优先级对象;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Nullable
	protected String determineHighestPriorityCandidate(Map<String, Object> candidates, Class<?> requiredType) {
		String highestPriorityBeanName = null;
		Integer highestPriority = null;
		for (Map.Entry<String, Object> entry : candidates.entrySet()) {
			String candidateBeanName = entry.getKey();
			Object beanInstance = entry.getValue();
			if (beanInstance != null) {
				Integer candidatePriority = getPriority(beanInstance);
				if (candidatePriority != null) {
					if (highestPriorityBeanName != null) {
						if (candidatePriority.equals(highestPriority)) {
							throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(),
									"Multiple beans found with the same priority ('" + highestPriority +
									"') among candidates: " + candidates.keySet());
						}
						else if (candidatePriority < highestPriority) {
							highestPriorityBeanName = candidateBeanName;
							highestPriority = candidatePriority;
						}
					}
					else {
						highestPriorityBeanName = candidateBeanName;
						highestPriority = candidatePriority;
					}
				}
			}
		}
		return highestPriorityBeanName;
	}
}

isPrimary 方法返回 beanName 参数对应的类型对象是否使用 Primary 注解进行修饰;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	protected boolean isPrimary(String beanName, Object beanInstance) {
		String transformedBeanName = transformedBeanName(beanName);
		if (containsBeanDefinition(transformedBeanName)) {
			return getMergedLocalBeanDefinition(transformedBeanName).isPrimary();
		}
		BeanFactory parent = getParentBeanFactory();
		return (parent instanceof DefaultListableBeanFactory &&
				((DefaultListableBeanFactory) parent).isPrimary(transformedBeanName, beanInstance));
	}
}

getPriority 方法用于获取 beanName 参数对应的类型对象上是否使用 Order 注解进行修饰,拥有时直接返回注解值,否则返回 null;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	@Nullable
	protected Integer getPriority(Object beanInstance) {
		Comparator<Object> comparator = getDependencyComparator();
		if (comparator instanceof OrderComparator) {
			return ((OrderComparator) comparator).getPriority(beanInstance);
		}
		return null;
	}
}

matchesBeanName 方法返回 candidateName 是否与 beanName 参数相等或为其别名;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	protected boolean matchesBeanName(String beanName, @Nullable String candidateName) {
		return (candidateName != null &&
				(candidateName.equals(beanName) || ObjectUtils.containsElement(getAliases(beanName), candidateName)));
	}
}

isSelfReference 方法返回 candidateName 是否与 beanName 参数相等或为其工厂对象名;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	private boolean isSelfReference(@Nullable String beanName, @Nullable String candidateName) {
		return (beanName != null && candidateName != null &&
				(beanName.equals(candidateName) || (containsBeanDefinition(candidateName) &&
						beanName.equals(getMergedLocalBeanDefinition(candidateName).getFactoryBeanName()))));
	}
}

createOptionalDependency 方法首先使用 descriptor 参数创建 NestedDependencyDescriptor 对象,并使用该对象执行 doResolveDependency 方法解析依赖结果,在其为 Optional 对象时直接返回该值,否则使用 Optional 方法封装该对象并返回;

java 复制代码
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	private Optional<?> createOptionalDependency(
			DependencyDescriptor descriptor, @Nullable String beanName, final Object... args) {

		DependencyDescriptor descriptorToUse = new NestedDependencyDescriptor(descriptor) {
			@Override
			public boolean isRequired() {
				return false;
			}
			@Override
			public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory) {
				return (!ObjectUtils.isEmpty(args) ? beanFactory.getBean(beanName, args) :
						super.resolveCandidate(beanName, requiredType, beanFactory));
			}
		};
		Object result = doResolveDependency(descriptorToUse, beanName, null, null);
		return (result instanceof Optional ? (Optional<?>) result : Optional.ofNullable(result));
	}
}
相关推荐
Octopus20776 分钟前
链地址法(哈希桶)
c++·笔记·学习·算法·哈希算法
一只小萌新.15 分钟前
【Python学习(七)——序列、列表、元组、range、字符串、字典、集合、可变类型&不可变类型】
开发语言·python·学习
大丈夫立于天地间25 分钟前
OSPF - 影响OSPF邻居建立的因素
网络·网络协议·学习·智能路由器·信息与通信
龚子亦1 小时前
Unity学习之UGUI(二)
学习·unity·游戏引擎
Jackilina_Stone2 小时前
【HUAWEI】HCIP-AI-MindSpore Developer V1.0 | 第四章 图像处理原理与应用(2 图像预处理技术) | 学习笔记
图像处理·人工智能·笔记·学习·计算机视觉·huawei
yz7172 小时前
计算机网络•自顶向下方法:无线网络
网络·学习·计算机网络
123yhy传奇3 小时前
【学习总结|DAY028】后端Web实战(部门管理)
java·学习·mysql·log4j·maven·mybatis·web
PyAIGCMaster5 小时前
docker学习记录:部署es+kibana
学习·elasticsearch·docker
蜗牛_snail5 小时前
学习笔记 : MySQL进阶篇一之架构和日志文件
笔记·学习·mysql
小大力5 小时前
简单的jmeter数据请求学习
java·学习·jmeter