相关文章
Spring IOC系列学习笔记一:前置刷新
Spring IOC系列学习笔记二:obtainFreshBeanFactory方法
Spring IOC系列学习笔记三:parseDefaultElement详解
Spring IOC系列学习笔记四:parseCustomElement解析
Spring IOC系列学习笔记五:context:component-scan 节点解析
Spring IOC系列学习笔记六:invokeBeanFactoryPostProcessors解析
Spring IOC系列学习笔记七:registerBeanPostProcessors
Spring IOC系列学习笔记八:finishBeanFactoryInitialization
Spring IOC系列学习笔记九:getBean方法
Spring IOC系列学习笔记十:createBean方法(上)
Spring IOC系列学习笔记十一:createBean方法(下)
Spring IOC系列学习笔记十二:@Autowire注解
文章目录
- 相关文章
- 前言
- 代码块一:applyMergedBeanDefinitionPostProcessors
- 代码块二:getEarlyBeanReference
- 代码块三:addSingletonFactory
- 代码块四:populateBean
- 代码块五:autowireByName
- 代码块六:unsatisfiedNonSimpleProperties
- 代码块七:autowireByType
- 代码块八:applyPropertyValues
- 代码块九:initializeBean
- 代码块十:invokeAwareMethods
- 代码块十一:invokeInitMethods
- 代码块十二:invokeCustomInitMethod
- 代码块十三:applyBeanPostProcessorsBeforeInitialization&applyBeanPostProcessorsAfterInitialization
- 总结
前言
前面讲解了创建Bean实例的createBeanInstance方法,下面我们对doCreateBean其他方法进行解析。
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
1、bean的包装类
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
1.1、判断beanName是否是factoryBean,如果是则移除未完成bean的缓存
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
2、如果不是factoryBean则创建beanName的包装类
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
3.1、获取bean实例
final Object bean = instanceWrapper.getWrappedInstance();
3.2、获取bean的实例类型
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
3.3、如果bean实例的类型不是空则设置实例类型到mbd
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
4.1、MergedBeanDefinitionPostProcessor的后置处理,允许修改bean
4.2、@Autowired正式通过这儿预解析的
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.
5.1、判断bean是否提前早期循环引用,提前曝光。
5.2、mbd是单例的&&允许循环依赖&&当前bean正在被创建
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
6.1、getEarlyBeanReference:利用SmartInstantiationAwareBeanPostProcessor的后置处理返回bean的早期引用,如果没有则返回bean本身
6.2、提前曝光bean,添加到单例工厂解决循环引用
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
7、属性填充
populateBean(beanName, mbd, instanceWrapper);
8、初始化bean
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);
}
}
9.1、如果允许早期曝光,进行循环依赖检查
if (earlySingletonExposure) {
9.2、earlySingletonReference在存在循环依赖的情况下不为null
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
9.3、如果在初始化bean的时候没有改变bean对象,则不影响之前的循环引用
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
9.4、如果bean在初始化的时候被改变了,则原先的循环引用受影响,因为引用的是旧数据需要剔除掉,引用最新的bean对象
9.5、获取依赖于当前beanName的所有的bean的Name数组
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
9.6、尝试移除这些bean的实例,因为这些bean依赖的bean已经被增强了,他们依赖的bean相当于脏数据
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
9.7、移除失败的添加到actualDependentBeans中
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
9.8、如果存在移除失败的,则抛出异常,因为存在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.
try {
10、注册用于销毁的bean,执行销毁操作的有三种:自定义destroy方法、DisposableBean接口、DestructionAwareBeanPostProcessor
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
11、返回创建的bean
return exposedObject;
}
4.1、MergedBeanDefinitionPostProcessor的后置处理,允许修改bean见代码块一
6.1、getEarlyBeanReference:利用SmartInstantiationAwareBeanPostProcessor的后置处理返回bean的早期引用,如果没有则返回bean本身见代码块二
6.2、提前曝光bean,添加到单例工厂解决循环引用见代码块三
7、属性填充见代码块见代码块四
8、初始化bean见代码块九
代码块一:applyMergedBeanDefinitionPostProcessors
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {
1、对某些bean进行后置处理,@Autowire注解在这边对元数据进行预解析
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
代码块二:getEarlyBeanReference
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;
1、利用SmartInstantiationAwareBeanPostProcessor获取bean的早期引用,默认返回bean本身
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
return exposedObject;
}
代码块三:addSingletonFactory
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
1、singletonObjects不存在beanName的缓存
if (!this.singletonObjects.containsKey(beanName)) {
2、把beanName和他的单例工厂放到singletonFactories缓存中,singletonFactories就是spring中的三级缓存
this.singletonFactories.put(beanName, singletonFactory);
3、从earlySingletonObjects移除 earlySingletonObjects(beanName->bean的早期单例对象)
this.earlySingletonObjects.remove(beanName);
4、将beanName注册到registeredSingletons缓存(已注册的单例集合)
this.registeredSingletons.add(beanName);
}
}
}
代码块四:populateBean
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
1、如果bw为空,mbd有属性值则抛出异常,反之直接返回
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.
2、用于标识是否继续之后的属性填充
boolean continueWithPropertyPopulation = true;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
3、在bean实例化之后,属性填充之前调用,允许修改bean属性,默认返回true,如果返回false代表跳过之后的属性填充
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
if (!continueWithPropertyPopulation) {
return;
}
4、获取属性值
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
5、通过名字注入或者通过类型注入
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
5.1、通过名字注入
// Add property values based on autowire by name if applicable.
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
5.2、通过类型注入
// Add property values based on autowire by type if applicable.
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
6、BeanFactory是否注册过InstantiationAwareBeanPostProcessors
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
7、是否需要依赖检查
boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
8、注册过InstantiationAwareBeanPostProcessors或者需要依赖检查
if (hasInstAwareBpps || needsDepCheck) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
8.1、参数的属性
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
8.2、进行属性填充前的再次处理。例子:现在最常用的@Autowire属性注入就是这边注入依赖的bean实例对象
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
8.3、依赖检查,对应depends-on属性
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
if (pvs != null) {
9、填充上述处理后的属性值
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
5.1、通过名字注入见代码块五
5.2、通过类型注入见代码块七
9、填充上述处理后的属性值见代码块八
代码块五:autowireByName
protected void autowireByName(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
1、过滤mbd的简单属性值,非简单属性就是类型是对象的属性,但是八个原始类型不会拿到
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
2、如果容器中包含指定的bean,则直接拿到它
if (containsBean(propertyName)) {
Object bean = getBean(propertyName);
3、添加到pvs中
pvs.add(propertyName, bean);
4、注册依赖关系
registerDependentBean(propertyName, beanName);
if (logger.isDebugEnabled()) {
logger.debug("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");
}
}
}
}
1、过滤mbd的简单属性值见代码块六
4、注册依赖关系见Spring IOC系列学习笔记九:getBean方法的代码块八
代码块六:unsatisfiedNonSimpleProperties
protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) {
Set<String> result = new TreeSet<>();
1、获取mbd的属性值
PropertyValues pvs = mbd.getPropertyValues();
2、拿到bw的PropertyDescriptor
PropertyDescriptor[] pds = bw.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
if (pd.getWriteMethod() != null 2.1、有可写入属性的方法
&& !isExcludedFromDependencyCheck(pd) 2.2、不排除依赖检查的属性
&& !pvs.contains(pd.getName()) 2.3、pvs中不包括pd的beanName
&& !BeanUtils.isSimpleProperty(pd.getPropertyType())) 2.4、pd不是简单的类型
{
3、符合条件放入到result中
result.add(pd.getName());
}
}
return StringUtils.toStringArray(result);
}
代码块七:autowireByType
protected void autowireByType(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
1、获取类型转换器
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
2、寻找需要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.
3、属性类型不是object的类型
if (Object.class != pd.getPropertyType()) {
4、探测指定属性的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());
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
5、解析当前属性所匹配的bean实例,并把解析到的bean实例的beanName存储在autowiredBeanNames中
Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
if (autowiredArgument != null) {
pvs.add(propertyName, autowiredArgument);
}
6、注册依赖关系
for (String autowiredBeanName : autowiredBeanNames) {
registerDependentBean(autowiredBeanName, beanName);
if (logger.isDebugEnabled()) {
logger.debug("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);
}
}
}
代码块八:applyPropertyValues
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
1、pvs是空的话,无需属性注入直接返回
if (pvs.isEmpty()) {
return;
}
MutablePropertyValues mpvs = null;
List<PropertyValue> original;
if (System.getSecurityManager() != null) {
if (bw instanceof BeanWrapperImpl) {
((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
}
}
2、同样先判断pvs是不是已经封装MutablePropertyValues
if (pvs instanceof MutablePropertyValues) {
mpvs = (MutablePropertyValues) pvs;
2.1、属性是否已经转换
if (mpvs.isConverted()) {
// Shortcut: use the pre-converted values as-is.
try {
2.2、直接设置属性值
bw.setPropertyValues(mpvs);
return;
}
catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
2.2、未转换设置原始属性值,后续对原始属性进行转换和封装
original = mpvs.getPropertyValueList();
}
else {
original = Arrays.asList(pvs.getPropertyValues());
}
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
3、获取对应的解析器
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;
4、遍历属性,将属性转换为相应的类型
for (PropertyValue pv : original) {
if (pv.isConverted()) {
4.1、已经转换直接放入到缓存中
deepCopy.add(pv);
}
else {
4.2、拿到属性名字
String propertyName = pv.getName();
4.3、拿到属性值
Object originalValue = pv.getValue();
4.4、解析属性值
Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
Object convertedValue = resolvedValue;
4.5、属性值是否可以转换
boolean convertible = bw.isWritableProperty(propertyName) &&
!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
if (convertible) {
4.6、进行属性转换
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.
4.7、在合并的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));
}
}
}
5、都已经转换完毕的标志
if (mpvs != null && !resolveNecessary) {
mpvs.setConverted();
}
// Set our (possibly massaged) deep copy.
try {
6、设置bean的属性值为deepCopy
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
}
catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
流程:
- 检测属性值列表是否已转换过的,若转换过,则直接填充属性,无需再次转换
- 遍历属性值列表 pvs,解析原始值 originalValue,得到解析值 resolvedValue 对解析后的属性值
resolvedValue 进行类型转换 - 将类型转换后的属性值设置到 PropertyValue 对象中,并将 PropertyValue 对象存入 deepCopy 集合中
- 将 deepCopy 中的属性信息注入到 bean 对象中
上面的属性注入只是完成了属性的获取,将获取的属性封装在PropertyValues对象中,并没有应用到已经实例化的bean上,而applyPropertyValues方法就是完成这一操作的。
到这儿属性注入结束,下面进入初始化bean
代码块九:initializeBean
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
1、实现Aware方法的处理
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
2、初始化前对bean进行包装,调用前置处理
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
3、初始化方法
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、初始化后后置处理
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
1、实现Aware方法的处理,见代码块十
3、初始化方法 见代码块十一
2和4、BeanPostProcessor的处理见代码块十三
代码块十:invokeAwareMethods
private void invokeAwareMethods(final String beanName, final Object bean) {
1、是否实现了Aware接口
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
2、如果实现了BeanNameAware,则设置beanName,下面同理
((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
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
1、首先检查bean是否实现了InitializingBean接口,如果是的话调用afterPropertiesSet方法
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isDebugEnabled()) {
logger.debug("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) {
2、获取初始化方法名
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
3、自定义初始化方法
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
3、自定义初始化方法见代码块十二
代码块十二:invokeCustomInitMethod
protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {
1、获取初始化方法名
String initMethodName = mbd.getInitMethodName();
Assert.state(initMethodName != null, "No init method set");
2、根据方法名拿到方法
final Method initMethod = (mbd.isNonPublicAccessAllowed() ?
BeanUtils.findMethod(bean.getClass(), initMethodName) :
ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));
if (initMethod == null) {
if (mbd.isEnforceInitMethod()) {
throw new BeanDefinitionValidationException("Couldn't find an init method named '" +
initMethodName + "' on bean with name '" + beanName + "'");
}
else {
if (logger.isDebugEnabled()) {
logger.debug("No default init method named '" + initMethodName +
"' found on bean with name '" + beanName + "'");
}
// Ignore non-existent default lifecycle methods.
return;
}
}
if (logger.isDebugEnabled()) {
logger.debug("Invoking init method '" + initMethodName + "' on bean with name '" + beanName + "'");
}
3、调用方法
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();
}
}
}
代码块十三:applyBeanPostProcessorsBeforeInitialization&applyBeanPostProcessorsAfterInitialization
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
// 1.遍历所有注册的BeanPostProcessor实现类,调用postProcessBeforeInitialization方法
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
// 2.在bean初始化方法执行前,调用postProcessBeforeInitialization方法
result = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
------------------------------------------------------------------------------------------------------
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
// 1.遍历所有注册的BeanPostProcessor实现类,调用postProcessAfterInitialization方法
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
// 2.在bean初始化方法执行后,调用postProcessAfterInitialization方法
result = beanProcessor.postProcessAfterInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
总结
至此,finishBeanFactoryInitialization 方法解析完毕,我们通过 Spring IoC:finishBeanFactoryInitialization详解、Spring IoC:getBean详解、Spring IoC:createBean详解(上)和本文共四篇文章来介绍 finishBeanFactoryInitialization 方法。在 finishBeanFactoryInitialization 方法中,我们主要做了以下操作:
- 将之前解析的 BeanDefinition 进一步处理,将有父 BeanDefinition 的进行合并,获得
MergedBeanDefinition - 尝试从缓存获取 bean 实例
- 处理特殊的 bean —— FactoryBean 的创建
- 创建 bean 实例
- 循环引用的处理
- bean 实例属性填充
- bean 实例的初始化
- BeanPostProcessor 的各种扩展应用
finishBeanFactoryInitialization 方法解析的结束,也标志着 Spring IoC 整个构建过程中,重要的内容基本都已经解析完毕。