概述
接前文的getBean方法,我们这里展开解析里边的createBean方法。
createBean
createBean方法 在AbstractAutowireCapableBeanFactory类中
@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.
// 确保此时bean类已经被解析,并且克隆 bean 定义,以防动态解析的类不能存储在共享合并 bean 定义中。
// 锁定 class,根据设置的 class 属性或者根据 className 来解析 Class
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
//使用mdb深拷贝一个新的RootBeanDefinition副本,将解析的Class赋值给拷贝的RootBeanDefinition副本的beanClass属性
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.
//注释1. 实例化前的处理,让 beanPostProcessor (InstantiationAwareBeanPostProcessor)有机会返回代理而不是目标bean实例
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
// "短路",如果bean不为空,则直接使用返回的bean
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
//注释2 创建Bean实例
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);
}
}
注释1. 实例化前的处理,让 beanPostProcessor (InstantiationAwareBeanPostProcessor)有机会返回代理而不是目标bean实例 (见源码解析1)
注释2. 创建Bean实例,doCreateBean是真正干活的方法(见源码解析2)
【源码解析1】 resolveBeforeInstantiation方法
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
// 确保这个 bean 已经被解析了,没有解析将不会进行代理
//如果mbd不是合成的,并且BeanFactory中存在InstantiationAwareBeanPostProcessor
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
//注释1 执行前置拦截器的操作
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
// 执行后置拦截器的操作
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
注释1 执行前置处理器的操作 applyBeanPostProcessorsBeforeInstantiation,如果代理生成bean则执行后置处理器的操作:applyBeanPostProcessorsAfterInitialization
//执行后置处理器的操作
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
//遍历所有注册的BeanPostProcessor实现类
for (BeanPostProcessor bp : getBeanPostProcessors()) {
//是否实现了 InstantiationAwareBeanPostProcessor 接口
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
//注释1. 执行postProcessBeforeInstantiation方法
//该方法可以返回一个构造完成的Bean实例,从而不会继续执行创建Bean实例的“正规的流程”,达到“短路”的效果。
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
return null;
}
//执行后置处理器的操作,前文也已经解析过一次,在postProcessObjectFromFactoryBean那里
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
//遍历所有注册的BeanPostProcessor实现类,调用postProcessAfterInitialization方法
for (BeanPostProcessor processor : getBeanPostProcessors()) {
//在bean初始化后,调用postProcessAfterInitialization方法
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
//如果返回null,则直接返回结果
return result;
}
//有值则直接返回
result = current;
}
return result;
}
注释1. 这里经过调用InstantiationAwareBeanPostProcessor中的postProcessBeforeInstantiation方法,生成的bean实例是代理对象。这里涉及到AOP方面的东西。我们就简单拿一个InstantiationAwareBeanPostProcessor的实现类AbstractAutoProxyCreator,来看一下里边重写的postProcessBeforeInstantiation方法吧
postProcessBeforeInstantiation其他的就不在这里展开了,这个名字很熟悉吧proxy,代理。
【源码解析2】 真正创建 bean 实例:doCreateBean方法 重点方法
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
//新建Bean包装类
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
//如果是单例的FactoryBean,则需要先移除未完成的FactoryBean实例的缓存
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 注释1. 根据指定 bean 使用对应的策略创建新的实例
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
// 获取前面创建好的Bean实例
final Object bean = instanceWrapper.getWrappedInstance();
//获取Bean实例的类型
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
// 允许后置处理器修改合并的bean定义
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
//注释2. 应用后置处理器MergedBeanDefinitionPostProcessor
//执行修改MergedBeanDefinition
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.
//注释3. 是否需要提前曝光,用来解决循环依赖时使用
//条件:单例 && 允许循环依赖 && 当前bean正在创建中
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");
}
// 注释4 将缓存中的 bean 信息更新,解决循环依赖,传入beanName,和匿名函数
// 匿名函数实现函数式接口ObjectFactory的getObject方法,执行getEarlyBeanReference
//getEarlyBeanReference:应用后置处理器SmartInstantiationAwareBeanPostProcessor
//允许返回指定bean的早期引用,若没有则直接返回bean
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
// 初始化bean实例
Object exposedObject = bean;
try {
//注释5. 对 bean 进行填充,将各个属性值注入
// 如果存在对其它 bean 的依赖,将会递归初始化依赖的 bean
populateBean(beanName, mbd, instanceWrapper);
//注释6 调用初始化方法,例如 init-method
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);
}
}
//注释7. 如果允许提前曝光实例
if (earlySingletonExposure) {
//earlySingletonReference 缓存获取(获取三级缓存singletonFactories的值)
Object earlySingletonReference = getSingleton(beanName, false);
//注释7-1.earlySingletonReference 只有在检测到有循环依赖的情况下才 不为空
if (earlySingletonReference != null) {
if (exposedObject == bean) {
//注释7-2. 如果 exposedObject 没有在初始化方法中被改变,也就是没有被增强
exposedObject = earlySingletonReference;
}
//注释7-3. 如果exposedObject在initializeBean方法中被增强 && 不允许在循环引用的情况下使用注入原始bean实例,&&当前bean有被其他bean依赖
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
//注释7-4. 获取依赖当前bean的所有bean的beanName数组
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
// 注释7-5检查依赖
// 尝试移除这些bean的实例,因为这些bean依赖的bean已经被增强了
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
//把移除失败的添加到 actualDependentBeans集合里
actualDependentBeans.add(dependentBean);
}
}
// bean 创建后,它所依赖的 bean 一定是已经创建了
// 在上面已经找到它有依赖的 bean,如果 actualDependentBeans 不为空
// 表示还有依赖的 bean 没有初始化完成,也就是存在循环依赖
if (!actualDependentBeans.isEmpty()) {
//如果存在移除失败的,则抛出异常,因为存在bean依赖了“脏数据”
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 " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
// 根据 scope 注册用于销毁的 bean
try {
//注释8. 注册用于销毁的bean,执行销毁操作的有三种:自定义destroy方法、DisposableBean接口、DestructionAwareBeanPostProcessor
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
//完成创建并返回实例
return exposedObject;
}
注释1. 根据指定 bean 使用对应的策略创建新的实例——createBeanInstance(见源码解析3)
注释2. 执行修改MergedBeanDefinition——applyMergedBeanDefinitionPostProcessors(见源码解析4)
注释4. 将缓存中的 bean 信息更新——addSingletonFactory(见源码解析5)
传入beanName,和匿名函数,匿名函数实现函数式接口ObjectFactory的getObject方法,执行getEarlyBeanReference方法——(见源码解析5-1)
注释5. 对 bean 进行填充,将各个属性值注入如果存在对其它 bean 的依赖,将会递归初始化依赖的 bean——populateBean方法(见源码解析6)
注释6. 调用初始化方法(见源码解析7)
注释7. 进行循环依赖检查
获取earlySingletonReference 只有在当前解析的 bean 存在循环依赖的情况下才会不为空。
因为如果不是循环依赖,只会在完全创建完 bean 实例才会添加到 singletonObjects 缓存。此时,我们正在创建 bean 的过程中,还没有完全创建完,singletonObjects 缓存是肯定没有当前 beanName 的;而如果不存在循环引用,从 doGetBean 方法开始,getSingleton 方法只会在最初 doGetBean 方法里调用一次,不存在循环引用,也就用不到提前曝光的 ObjectFactory 来创建 bean 对象,从而 earlySingletonObjects 缓存肯定也是没有 beanName 的 bean 实例对象的,所以必然返回空。
注释8. 注册用于销毁的bean——registerDisposableBeanIfNecessary方法(见源码解析8)
【源码解析3】 createBeanInstance方法
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
//解析bean的类型信息
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);
}
//如果存在工厂方法则使用工厂方法实例化bean对象(基本不用)
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
// resolved: 构造函数或工厂方法是否已经解析过
boolean resolved = false;
//autowireNecessary: 是否需要自动注入(即是否需要解析构造函数参数)
boolean autowireNecessary = false;
if (args == null) {
//加锁
synchronized (mbd.constructorArgumentLock) {
// 如果resolvedConstructorOrFactoryMethod不为空
if (mbd.resolvedConstructorOrFactoryMethod != null) {
//将resolved标记为已解析
resolved = true;
//根据constructorArgumentsResolved判断是否需要自动注入
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
// 如果已经解析过,不需要再次解析
//使用resolvedConstructorOrFactoryMethod缓存里解析好的构造函数方法
if (resolved) {
//需要自动注入
if (autowireNecessary) {
// 实际解析的是 org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor
// 构造函数自动注入
return autowireConstructor(beanName, mbd, null, null);
}
else {
// 使用默认的构造函数
return instantiateBean(beanName, mbd);
}
}
//注释1. 应用后置处理器SmartInstantiationAwareBeanPostProcessor,拿到bean的候选构造函数
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
//注释2. 如果ctors不为空
//或 mbd的注入方式为AUTOWIRE_CONSTRUCTOR
//或 mdb定义了构造函数的参数值 || args不为空
//则执行构造函数自动注入
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);
}
创建实例的方法通常有以下几种:工厂方法、构造函数自动装配(通常指带有参数的构造函数)、简单实例化(默认的构造函数)
注释1. 应用后置处理器 SmartInstantiationAwareBeanPostProcessor,拿到给定 bean 的候选构造函数——determineConstructorsFromBeanPostProcessors方法(见源码解析3-1)
注释2. 执行构造函数自动注入——autowireConstructor方法(见源码解析3-2)
【源码解析3-1】 determineConstructorsFromBeanPostProcessors方法
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
throws BeansException {
if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
//遍历所有的BeanPostProcessor
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
//注释1. 调用SmartInstantiationAwareBeanPostProcessor的determineCandidateConstructors方法
//该方法可以返回要用于beanClass的候选构造函数
//例如:使用@Autowire注解修饰构造函数
//则该构造函数在这边会被AutowiredAnnotationBeanPostProcessor找到
Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
if (ctors != null) {
//如果ctors不为空,则直接返回构造函数
return ctors;
}
}
}
}
return null;
}
注释1. 调用 SmartInstantiationAwareBeanPostProcessor 的 determineCandidateConstructors 方法,该方法可以返回要用于 beanClass 的候选构造函数。比如使用 @Autowire 注解修饰构造函数,则该构造函数在这边会被 AutowiredAnnotationBeanPostProcessor 找到。
【源码解析3-2】 autowireConstructor方法,具体调用的是ConstructorResolver类中的方法
protected BeanWrapper autowireConstructor(
String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] ctors, @Nullable Object[] explicitArgs) {
return new ConstructorResolver(this).class ConstructorResolver(beanName, mbd, ctors, explicitArgs);
}
//具体在ConstructorResolver类中执行: 自动匹配构造函数,有点复杂
public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd,
@Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {
// 注释. 定义一个bean的包装类
// 即创建一个BeanWrapperImpl对象(BeanWrapper接口的实现类对象)
BeanWrapperImpl bw = new BeanWrapperImpl();
this.beanFactory.initBeanWrapper(bw);
//最终用于实例化的构造函数
Constructor<?> constructorToUse = null;
//最终用于实例化的参数Holder
ArgumentsHolder argsHolderToUse = null;
//最终用于实例化的构造函数参数
Object[] argsToUse = null;
//explicitArgs不为空,则解析出要用于实例化的构造函数参数
if (explicitArgs != null) {
argsToUse = explicitArgs;
}
else {
//尝试从缓存中获取已经解析过的构造函数参数
Object[] argsToResolve = null;
//加锁
synchronized (mbd.constructorArgumentLock) {
//获取缓存中已解析的构造函数或工厂方法
constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
//如果constructorToUse不为空 && mbd标记了构造函数参数已解析
if (constructorToUse != null && mbd.constructorArgumentsResolved) {
//从mbd中获取已解析的构造函数参数resolvedConstructorArguments
argsToUse = mbd.resolvedConstructorArguments;
//如果argsToUse 为空
if (argsToUse == null) {
//从mbd中获取准备用于解析的构造函数参数preparedConstructorArguments
argsToResolve = mbd.preparedConstructorArguments;
}
}
}
//如果argsToResolve不为空,则对构造函数参数进行解析
if (argsToResolve != null) {
//对构造函数参数进行解析
argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve, true);
}
}
//如果缓存中获取不到构造函数或构造函数参数
if (constructorToUse == null || argsToUse == null) {
// Take specified constructors, if any.
//定义一个构造函数数组candidates 将chosenCtors赋值给它
Constructor<?>[] candidates = chosenCtors;
//如果candidates 为空
if (candidates == null) {
//从mbd里获取bean Class
Class<?> beanClass = mbd.getBeanClass();
try {
//mbd里是否允许访问非公共构造函数和方法
//如果是,则candidates 为所有声明的构造函数
//如果不是,则candidates 为公共构造函数
candidates = (mbd.isNonPublicAccessAllowed() ?
beanClass.getDeclaredConstructors() : beanClass.getConstructors());
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Resolution of declared constructors on bean Class [" + beanClass.getName() +
"] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
}
}
//如果candidates长度,即只有一个构造函数
//并且explicitArgs 为空
//并且mbd的hasConstructorArgumentValues为false,即无构造函数参数
if (candidates.length == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) {
//唯一的构造函数
Constructor<?> uniqueCandidate = candidates[0];
//如果这个构造函数无参数
if (uniqueCandidate.getParameterCount() == 0) {
//加锁操作
synchronized (mbd.constructorArgumentLock) {
mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
mbd.constructorArgumentsResolved = true;
mbd.resolvedConstructorArguments = EMPTY_ARGS;
}
//将构造的实例加入BeanWrapper中
bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
//返回BeanWrapper对象
return bw;
}
}
// Need to resolve the constructor(需要通过解析配置文件,获取构造函数)
//检查是否需要自动装配:
//chosenCtors不为空 或 从mbd里获取的 autowireMode为AUTOWIRE_CONSTRUCTOR
boolean autowiring = (chosenCtors != null ||
mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
ConstructorArgumentValues resolvedValues = null;
//构造函数参数个数
int minNrOfArgs;
if (explicitArgs != null) {
//explicitArgs不为空,则使用explicitArgs的length作为minNrOfArgs的值
minNrOfArgs = explicitArgs.length;
}
else {
//注释. 以下这部分解析mbd中的构造函数参数值,主要是处理我们通过xml方式定义的构造函数注入的参数
//如果我们是通过@Autowire注解直接修饰构造函数,则mbd是没有这些参数值的
// 获得mbd的构造函数的参数值
// indexedArgumentValues:带index的参数值;genericArgumentValues:通用的参数值
ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
//创建ConstructorArgumentValues对象resolvedValues,用于承载解析后的构造函数参数的值
resolvedValues = new ConstructorArgumentValues();
//解析mbd的构造函数的参数,并返回参数个数
minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
}
//对给定的构造函数排序
AutowireUtils.sortConstructors(candidates);
//最小匹配权重,权重越小,越接近我们要找的目标构造函数
int minTypeDiffWeight = Integer.MAX_VALUE;
Set<Constructor<?>> ambiguousConstructors = null;
LinkedList<UnsatisfiedDependencyException> causes = null;
//遍历所有构造函数候选者,找出符合条件的构造函数
for (Constructor<?> candidate : candidates) {
//拿到当前遍历的构造函数的参数类型数组
Class<?>[] paramTypes = candidate.getParameterTypes();
if (constructorToUse != null && argsToUse != null && argsToUse.length > paramTypes.length) {
// Already found greedy constructor that can be satisfied ->
// do not look any further, there are only less greedy constructors left.
//如果已经找到满足的构造函数 && 目标构造函数需要的参数个数大于当前遍历的构造函数的参数个数则终止
//因为遍历的构造函数已经排过序,后面不会有更合适的候选者了
break;
}
//如果当前遍历到的构造函数的参数个数小于我们所需的参数个数,则直接跳过该构造函数,继续下一个
if (paramTypes.length < minNrOfArgs) {
continue;
}
ArgumentsHolder argsHolder;
//存在参数则根据参数值来匹配参数类型
// resolvedValues不为空
if (resolvedValues != null) {
try {
//解析使用ConstructorProperties注解的构造函数参数
String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, paramTypes.length);
//如果获取的参数名称为空
if (paramNames == null) {
//获取参数名称解析器
ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
if (pnd != null) {
//使用参数名称解析器获取当前遍历的构造函数的参数名称
paramNames = pnd.getParameterNames(candidate);
}
}
//创建一个参数数组以调用构造函数或工厂方法
//主要是通过参数类型和参数名解析构造函数或工厂方法所需的参数(如果参数是其他bean,则会解析依赖的bean)
argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames,
getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1);
}
catch (UnsatisfiedDependencyException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex);
}
// Swallow and try next constructor.
if (causes == null) {
causes = new LinkedList<>();
}
causes.add(ex);
continue;
}
}
else {
// resolvedValues为空,则explicitArgs不为空,即给出了显式参数
// Explicit arguments given -> arguments length must match exactly.
//如果当前遍历的构造函数参数个数与explicitArgs长度不相同,则跳过该构造函数
if (paramTypes.length != explicitArgs.length) {
continue;
}
//使用显式给出的参数构造ArgumentsHolder
argsHolder = new ArgumentsHolder(explicitArgs);
}
//根据mbd的解析构造函数模式(true: 宽松模式(默认),false:严格模式)
//将argsHolder的参数和paramTypes进行比较,计算paramTypes的类型差异权重值
int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
// Choose this constructor if it represents the closest match.
//类型差异权重值越小,则说明构造函数越匹配,则选择此构造函数
if (typeDiffWeight < minTypeDiffWeight) {
constructorToUse = candidate;
argsHolderToUse = argsHolder;
argsToUse = argsHolder.arguments;
minTypeDiffWeight = typeDiffWeight;
//如果出现权重值更小的候选者,则将ambiguousConstructors清空,允许之前存在权重值相同的候选者
ambiguousConstructors = null;
}//如果存在两个候选者的权重值相同,并且是当前遍历过权重值最小的
else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
if (ambiguousConstructors == null) {
//将这两个候选者都添加到ambiguousConstructors
ambiguousConstructors = new LinkedHashSet<>();
ambiguousConstructors.add(constructorToUse);
}
ambiguousConstructors.add(candidate);
}
}
//如果最终没有找到匹配的构造函数,则进行异常处理
if (constructorToUse == null) {
if (causes != null) {
UnsatisfiedDependencyException ex = causes.removeLast();
for (Exception cause : causes) {
this.beanFactory.onSuppressedException(cause);
}
throw ex;
}
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Could not resolve matching constructor " +
"(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)");
}//如果找到了匹配的构造函数,但是存在多个(ambiguousConstructors不为空) && 解析构造函数的模式为严格模式,则抛出异常
else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Ambiguous constructor matches found in bean '" + beanName + "' " +
"(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " +
ambiguousConstructors);
}
if (explicitArgs == null && argsHolderToUse != null) {
argsHolderToUse.storeCache(mbd, constructorToUse);
}
}
Assert.state(argsToUse != null, "Unresolved constructor arguments");
//将构造的实例加入BeanWrapper中,并返回
bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
return bw;
}
这个方法有点长,里边有些分支方法不太好解析,先做个标记(TODO 待补充)
【源码解析4】 applyMergedBeanDefinitionPostProcessors方法
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
//获取BeanFactory中已注册的BeanPostProcessor,并遍历
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {
//调用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition方法
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
调用 MergedBeanDefinitionPostProcessor 的 postProcessMergedBeanDefinition 方法,对指定 bean 的给定MergedBeanDefinition进行后置处理。
例如AutowiredAnnotationBeanPostProcessor(@Autowire 注解在这边对元数据进行预解析)
【源码解析5】 之前解析过getSingleton方法,这里解析DefaultSingletonBeanRegistry类中的addSingletonFactory方法
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
// 判断 singletonObjects 不存在 beanName
if (!this.singletonObjects.containsKey(beanName)) {
//放入 beanName -> beanFactory,到时在 getSingleton() 获取单例时,可直接获取创建对应 bean 的工厂,解决循环依赖
this.singletonFactories.put(beanName, singletonFactory);
// 从提前曝光的缓存中移除,之前在 getSingleton() 放入的
this.earlySingletonObjects.remove(beanName);
// 往注册缓存中添加 beanName
this.registeredSingletons.add(beanName);
}
}
}
我们通过提前曝光的 ObjectFactory 获得 “不完整” 的 bean 实例,从而解决循环引用的问题,ObjectFactory 就是通过这边的 singletonObjects 缓存来进行曝光的。
这里的singletonFactory的getObject方法被重写了,会执行getEarlyBeanReference
【源码解析5-1】 getEarlyBeanReference方法
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
// 如果bean不为空 && mbd不是合成 && 存在InstantiationAwareBeanPostProcessors
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
//允许SmartInstantiationAwareBeanPostProcessor返回指定bean的早期引用
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
//返回要作为bean引用公开的对象,如果没有SmartInstantiationAwareBeanPostProcessor修改,则返回的是入参的bean对象本身
return exposedObject;
}
【源码解析6】 对 bean 进行属性填充:populateBean方法
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
//判断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.
// 给awareBeanPostProcessor 后处理器最后一次机会,在属性设置之前修改bean的属性
boolean continueWithPropertyPopulation = true;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
//在bean实例化后,属性填充之前被调用,允许修改bean的属性,如果返回false,则跳过之后的属性填充
//如果返回false,将continueWithPropertyPopulation赋值为false,跳出循环
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
// 短路操作,如果上面判断不能进行属性填充,将会跳过下面的程序
if (!continueWithPropertyPopulation) {
return;
}
// 定义一个pvs变量,就是bean要填充的属性
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
//注释1 解析自动装配模式为AUTOWIRE_BY_NAME和AUTOWIRE_BY_TYPE
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) {
//注释1-1 根据名字自动注入
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
//注释1-2 根据类型自动注入
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
// 是否有InstantiationAwareBeanPostProcessors后置处理器 标记
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
// 是否需要依赖检查标记
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
PropertyDescriptor[] filteredPds = null;
//注册过InstantiationAwareBeanPostProcessors后置处理器
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
// 从 beanPostProcessors 对象中提取 BeanPostProcessor 结果集,遍历后置处理器
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
//注释2. 执行应用后置处理器InstantiationAwareBeanPostProcessor的方法postProcessPropertyValues
//进行属性填充前的再次处理。
//例子:现在最常用的@Autowire属性注入就是这边注入依赖的bean实例对象
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) {
// 在前面也出现过,用来进行依赖检查(dependsOn属性)
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
checkDependencies(beanName, mbd, filteredPds, pvs);
}
if (pvs != null) {
//注释3. 前面做了这么多,这里才是真填充
// 将属性填充到 bean 中,使用深拷贝,将子类的属性一并拷贝
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
注释1-1 根据名字自动注入——autowireByName(见源码解析6-1)
注释1-2 根据类型自动注入——autowireByType(见源码解析6-2)
注释2 应用后置处理器 InstantiationAwareBeanPostProcessor 的方法 postProcessPropertyValues,进行属性填充前的再次处理。例如AutowiredAnnotationBeanPostProcessor,执行@Autowire 属性注入
注释3 将属性填充到 bean 中——applyPropertyValues(见源码解析6-3)
【源码解析6-1】 根据名字自动注入:autowireByName方法
protected void autowireByName(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
//寻找bw中需要依赖注入的属性
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
//遍历属性名
for (String propertyName : propertyNames) {
//校验是否存在beanName=propertyName的bean实例或者BeanDefinition
if (containsBean(propertyName)) {
//获取propertyName的bean实例对象
Object bean = getBean(propertyName);
//将属性名和属性值添加到pvs
pvs.add(propertyName, bean);
//注册依赖关系到缓存(beanName依赖propertyName 前面解析过这个方法。)
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");
}
}
}
}
【源码解析6-2】 根据类型自动注入:autowireByType方法
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);
//寻找bw中需要依赖注入的属性
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()) {
//获取指定属性的set方法,封装成MethodParameter(必须有set方法才能通过属性来注入)
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
// Do not allow eager init for type matching in case of a prioritized post-processor.
boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
//将MethodParameter的方法参数索引信息封装成DependencyDescriptor
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
//解析当前属性所匹配的bean实例,并把解析到的bean实例的beanName存储在autowiredBeanNames中
Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
if (autowiredArgument != null) {
//如果找到了依赖的bean实例,将属性名和bean实例放到pvs中
pvs.add(propertyName, autowiredArgument);
}
for (String autowiredBeanName : autowiredBeanNames) {
//注册依赖关系,beanName依赖autowiredBeanName
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);
}
}
}
【源码解析6-3】 这里才是将属性填充到 bean 中:applyPropertyValues方法
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) {
//强制转换MutablePropertyValues类型
mpvs = (MutablePropertyValues) pvs;
//如果mpvs中的值已经被转换为对应的类型,那么可以直接设置到BeanWrapper中
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 {
//如果pvs并不是使用MutablePropertyValues封装的类型,那么直接使用原始的属性获取方法
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()) {
//如果pv已经包含转换的值,则直接添加到deepCopy
deepCopy.add(pv);
}
else {
String propertyName = pv.getName();
Object originalValue = pv.getValue();
// 解析参数,如果是引用对象,将会进行提前加载
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.
//在合并的BeanDefinition中存储转换后的值,以避免为每个创建的bean实例重新转换
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 {
//设置bean的属性值为deepCopy
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
}
catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
【源码解析7】 initializeBean方法
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
// 注释1 securityManage 的作用是?
//激活Aware扩展中的方法
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
// 如果没有 securityManage,方法里面校验了 bean 的类型,需要引用 Aware 接口
// 对特殊的 bean 处理:Aware/ BeanClassLoader / BeanFactoryAware
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 熟悉么,后处理器又来了
// 注释2. bean 实例化阶段,调用已经注册好的 beanPostProcessor 的 postProcessBeforeInitialization 方法
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 注释3. 激活用户自定义的初始化方法 init-method 方法
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()) {
//注释4. bean 实例化阶段,调用已经注册好的 beanPostProcessor 的 postProcessAfterInitialization 方法
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
//返回包装过的bean对象
return wrappedBean;
}
注释1. System.getSecurityManager()需要好好调查下干什么用的。
激活Aware扩展中的方法,在Spring中以 Aware 为结尾的类都是一些扩展接口,用于提供给开发者获取到 BeanFactory 中的一些属性或对象。invokeAwareMethods(见源码解析7-1)
注释2、注释4 applyBeanPostProcessorsBeforeInitialization、applyBeanPostProcessorsAfterInitialization调用注册好的beanPostProcessor 的postProcessBeforeInitialization 、postProcessAfterInitialization 方法,它会出现在bean实例初始化的前后。(见源码解析7-2)
注释3. 调用初始化方法 (见源码解析7-3)
【源码解析7-1】 激活Aware扩展中的方法 : invokeAwareMethods
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
//BeanNameAware: 实现此接口的类想要拿到beanName,因此我们在这边赋值给它
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
//BeanClassLoaderAware:实现此接口的类想要拿到beanClassLoader,因此我们在这边赋值给它
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
//BeanFactoryAware: 实现此接口的类想要拿到 BeanFactory,因此我们在这边赋值给它
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
激活Aware扩展中的方法,在Spring中以 Aware 为结尾的类都是一些扩展接口,用于提供给开发者获取到 BeanFactory 中的一些属性或对象
【源码解析7-2】 applyBeanPostProcessorsBeforeInitialization、applyBeanPostProcessorsAfterInitialization 方法
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
//在bean初始化方法执行前,调用postProcessBeforeInitialization方法
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
// 在bean初始化方法执行后,调用postProcessAfterInitialization方法
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
这边提一个比较重要的实现类:ApplicationContextAwareProcessor(见源码解析7-2-1)
【源码解析7-2-1】
class ApplicationContextAwareProcessor implements BeanPostProcessor {
private final ConfigurableApplicationContext applicationContext;
private final StringValueResolver embeddedValueResolver;
/**
* Create a new ApplicationContextAwareProcessor for the given context.
*/
public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {
this.applicationContext = applicationContext;
this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());
}
@Override
@Nullable
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
AccessControlContext acc = null;
if (System.getSecurityManager() != null &&
(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
acc = this.applicationContext.getBeanFactory().getAccessControlContext();
}
if (acc != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareInterfaces(bean);
return null;
}, acc);
}
else {
invokeAwareInterfaces(bean);
}
return bean;
}
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof Aware) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
}
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
}
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
return bean;
}
}
我们经常通过实现 ApplicationContextAware 接口来拿到 ApplicationContext,我们之所以能拿到 ApplicationContext,就是因为ApplicationContextAwareProcessor 类里的applicationContext属性,它是在这边被赋值的。
【源码解析7-3】 调用初始化方法 invokeInitMethods方法
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
// 检查是否 InitializingBean类型,如果是的话需要调用 afterPropertiesSet 方法
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)) {
//注释1. 调用自定义初始化方法
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
注释1. 调用自定义初始化方法 ——invokeCustomInitMethod(见源码解析7-3-1)
【源码解析7-3-1】 调用用户自定义的初始化方法: invokeCustomInitMethod
protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {
//获取初始化方法的方法名
String initMethodName = mbd.getInitMethodName();
Assert.state(initMethodName != null, "No init method set");
final 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 + "'");
}
//调用初始化方法
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
ReflectionUtils.makeAccessible(initMethod);
return null;
});
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () ->
initMethod.invoke(bean), getAccessControlContext());
}
catch (PrivilegedActionException pae) {
InvocationTargetException ex = (InvocationTargetException) pae.getException();
throw ex.getTargetException();
}
}
else {
try {
ReflectionUtils.makeAccessible(initMethod);
initMethod.invoke(bean);
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}
※这里我们需要关注的一个接口是InitializingBean接口,如下:
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
例如我们有个TestBean实现这个接口
public class TestBean implements InitializingBean{
private UserService userService;
public TestBean(){
System.out.println("执行构造器方法");
}
public void testInitMethod(){
System.out.println("执行自定义配置的初始化方法");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("执行实现InitializingBean的初始化方法");
}
}
可以看到我们重写了afterPropertiesSet方法,然后在<bean> 里,我们可以配置指定init-method=testInitMethod。可以自己尝试一下。
【源码解析8】 注册用于销毁的bean : registerDisposableBeanIfNecessary方法,在AbstractBeanFactory类中
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
// mbd的scope不是prototype && 给定的bean需要在关闭时销毁
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
if (mbd.isSingleton()) {
// Register a DisposableBean implementation that performs all destruction
// work for the given bean: DestructionAwareBeanPostProcessors,
// DisposableBean interface, custom destroy method.
// 单例模式下注册用于销毁的bean到disposableBeans缓存,执行给定bean的所有销毁工作
// DestructionAwareBeanPostProcessors,DisposableBean接口,自定义销毁方法
// 注册 DisposableBean
registerDisposableBean(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
else {
//自定义scope处理
// A bean with a custom scope...
Scope scope = this.scopes.get(mbd.getScope());
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
}
scope.registerDestructionCallback(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
}
}
总结
到这里,finishBeanFactoryInitialization的解析才算结束。回顾一下整个finishBeanFactoryInitialization的流程是:
- 将之前解析的 BeanDefinition 进一步处理,将有父 BeanDefinition 的进行合并,获得 MergedBeanDefinition
- 尝试从缓存获取 bean 实例
- 处理特殊的 bean —— FactoryBean 的创建
- 创建 bean 实例
- 通过三级缓存的概念,来处理循环依赖
- bean 实例属性填充
-在初始化前后对BeanPostProcessor 的各种扩展实现 - bean 实例的初始化
以上就是SpringIoC的核心内容。之后将会总体回顾一下这些过程加深印象,然后解析@Autowired注解 和 Spring的事件监听机制就是之前提到 refresh过程中有一段关于事件和监听器的部分。
网友评论