spring 源码笔记 启动过程(十三) finishBeanFactoryInitialization(beanFactory)

第十三步:finishBeanFactoryInitialization(beanFactory)

第一次调用Bean后置处理器:判断Bean是否需要代理

第一次调用Bean后置处理器调用链

resolveBeforeInstantiation:1099, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBean:506, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
lambda$doGetBean 0 : 328 , A b s t r a c t B e a n F a c t o r y ( o r g . s p r i n g f r a m e w o r k . b e a n s . f a c t o r y . s u p p o r t ) g e t O b j e c t : − 1 , 1908143486 ( o r g . s p r i n g f r a m e w o r k . b e a n s . f a c t o r y . s u p p o r t . A b s t r a c t B e a n F a c t o r y 0:328, AbstractBeanFactory (org.springframework.beans.factory.support) getObject:-1, 1908143486 (org.springframework.beans.factory.support.AbstractBeanFactory 0:328,AbstractBeanFactory(org.springframework.beans.factory.support)getObject:1,1908143486(org.springframework.beans.factory.support.AbstractBeanFactory$Lambda$12)
getSingleton:229, DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
doGetBean:326, AbstractBeanFactory (org.springframework.beans.factory.support)
getBean:200, AbstractBeanFactory (org.springframework.beans.factory.support)
preInstantiateSingletons:854, DefaultListableBeanFactory (org.springframework.beans.factory.support)
finishBeanFactoryInitialization:889, AbstractApplicationContext (org.springframework.context.support)
refresh:553, AbstractApplicationContext (org.springframework.context.support)
main:9, AnnotationConfigApplication (com.tbryant.springtest.demo)

第一次调用Bean后置处理器入口
	protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
		Object bean = null;
		// mbd.beforeInstantiationResolvednull == null
		if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
			// Make sure bean class is actually resolved at this point.
			// 判断是否为合成类,99.9%不是
			// hasInstantiationAwareBeanPostProcessors() 默认为true
			if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
				// 拿到目标对象类型,通常不为null
				Class<?> targetType = determineTargetType(beanName, mbd);
				if (targetType != null) {
					// 第一次调用后置处理器 入口
					// 判断Bean是否需要代理
					bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
					// 如果不为空直接跳到第八次调用后置处理器,返回代理对象
					// spring内置的三个Bean后置处理器全部返回null,如果不扩展spring这里不会进
					if (bean != null) {
						bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
					}
				}
			}
			// 如果不扩展spring这里是false
			mbd.beforeInstantiationResolved = (bean != null);
		}
		return bean;
	}
ConfigurationClassPostProcessor.postProcessBeforeInstantiation
	public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
		return null;
	}
CommonAnnotationBeanPostProcessor.postProcessBeforeInstantiation
	public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
		return null;
	}
AutowiredAnnotationBeanPostProcessor.postProcessBeforeInstantiation
	public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
		return null;
	}

spring内置的Bean后置处理器全部返回null,因此如果想手动实现代理,可扩展此方法。

第二次调用Bean后置处理器:第一次推断构造方法

第二次调用Bean后置处理器调用链

createBeanInstance:1210, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
doCreateBean:558, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBean:517, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
lambda$doGetBean 0 : 328 , A b s t r a c t B e a n F a c t o r y ( o r g . s p r i n g f r a m e w o r k . b e a n s . f a c t o r y . s u p p o r t ) g e t O b j e c t : − 1 , 1908143486 ( o r g . s p r i n g f r a m e w o r k . b e a n s . f a c t o r y . s u p p o r t . A b s t r a c t B e a n F a c t o r y 0:328, AbstractBeanFactory (org.springframework.beans.factory.support) getObject:-1, 1908143486 (org.springframework.beans.factory.support.AbstractBeanFactory 0:328,AbstractBeanFactory(org.springframework.beans.factory.support)getObject:1,1908143486(org.springframework.beans.factory.support.AbstractBeanFactory$Lambda$12)
getSingleton:229, DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
doGetBean:326, AbstractBeanFactory (org.springframework.beans.factory.support)
getBean:200, AbstractBeanFactory (org.springframework.beans.factory.support)
preInstantiateSingletons:854, DefaultListableBeanFactory (org.springframework.beans.factory.support)
finishBeanFactoryInitialization:889, AbstractApplicationContext (org.springframework.context.support)
refresh:553, AbstractApplicationContext (org.springframework.context.support)
main:9, AnnotationConfigApplication (com.tbryant.springtest.demo)

第二次调用Bean后置处理器入口
	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表达式拿对象,一般为null
		Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
		if (instanceSupplier != null) {
			return obtainFromSupplier(instanceSupplier, beanName);
		}
		// 如果有工厂方法,那么就调用工厂方法,不需要spring实例化
		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?
		// 第二次调用后置处理器 入口,推断构造方法
		// 有且进有一个带参构造方法的情况下不为null
		// 有多个@Autowired(required = false)的构造方法的情况下不为null
		// 其他情况都为空
		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);
	}
ConfigurationClassPostProcessor.determineCandidateConstructors
	public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException {
		return null;
	}
AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors

第二次推断构造方法

第一次推断构造方法AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors方法与第二次推断构造方法ConstructorResolver.autowireConstructor方法请参考spring 两次推断构造方法

实例化对象

AbstractAutowireCapableBeanFactory.instantiateBean
	protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
		try {
			Object beanInstance;
			final BeanFactory parent = this;
			if (System.getSecurityManager() != null) {
				beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
								getInstantiationStrategy().instantiate(mbd, beanName, parent),
						getAccessControlContext());
			} else {
				// 实例化对象
				beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
			}
			BeanWrapper bw = new BeanWrapperImpl(beanInstance);
			initBeanWrapper(bw);
			return bw;
		} catch (Throwable ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
		}
	}
SimpleInstantiationStrategy.instantiate
	public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
		// Don't override the class with CGLIB if no overrides.
		if (!bd.hasMethodOverrides()) {
			Constructor<?> constructorToUse;
			synchronized (bd.constructorArgumentLock) {
				// 取之前推断出来的构造方法
				constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
				if (constructorToUse == null) {
					final Class<?> clazz = bd.getBeanClass();
					// 如果是接口直接throw
					if (clazz.isInterface()) {
						throw new BeanInstantiationException(clazz, "Specified class is an interface");
					}
					try {
						if (System.getSecurityManager() != null) {
							constructorToUse = AccessController.doPrivileged(
									(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
						}
						else {
							// 取默认构造方法
							constructorToUse = clazz.getDeclaredConstructor();
						}
						bd.resolvedConstructorOrFactoryMethod = constructorToUse;
					}
					catch (Throwable ex) {
						throw new BeanInstantiationException(clazz, "No default constructor found", ex);
					}
				}
			}
			return BeanUtils.instantiateClass(constructorToUse);
		}
		else {
			// Must generate CGLIB subclass.
			return instantiateWithMethodInjection(bd, beanName, owner);
		}
	}
BeanUtils.instantiateClass
	public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
		Assert.notNull(ctor, "Constructor must not be null");
		try {
			ReflectionUtils.makeAccessible(ctor);
			// 通过反射实例化对象
			return (KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(ctor.getDeclaringClass()) ? KotlinDelegate.instantiateClass(ctor, args) : ctor.newInstance(args));
		}
		catch (InstantiationException ex) {
			throw new BeanInstantiationException(ctor, "Is it an abstract class?", ex);
		}
		catch (IllegalAccessException ex) {
			throw new BeanInstantiationException(ctor, "Is the constructor accessible?", ex);
		}
		catch (IllegalArgumentException ex) {
			throw new BeanInstantiationException(ctor, "Illegal arguments for constructor", ex);
		}
		catch (InvocationTargetException ex) {
			throw new BeanInstantiationException(ctor, "Constructor threw exception", ex.getTargetException());
		}
	}

spring实例化对象的核心代码就是这句ctor.newInstance(args);至此,Bean对象实例化过程就结束了,后面进入Bean对象初始化过程。

第三次调用Bean后置处理器:合并父子BeanDefinition

第三次调用Bean后置处理器调用链

doCreateBean:572, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBean:517, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
lambda$doGetBean 0 : 328 , A b s t r a c t B e a n F a c t o r y ( o r g . s p r i n g f r a m e w o r k . b e a n s . f a c t o r y . s u p p o r t ) g e t O b j e c t : − 1 , 1908143486 ( o r g . s p r i n g f r a m e w o r k . b e a n s . f a c t o r y . s u p p o r t . A b s t r a c t B e a n F a c t o r y 0:328, AbstractBeanFactory (org.springframework.beans.factory.support) getObject:-1, 1908143486 (org.springframework.beans.factory.support.AbstractBeanFactory 0:328,AbstractBeanFactory(org.springframework.beans.factory.support)getObject:1,1908143486(org.springframework.beans.factory.support.AbstractBeanFactory$Lambda$12)
getSingleton:229, DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
doGetBean:326, AbstractBeanFactory (org.springframework.beans.factory.support)
getBean:200, AbstractBeanFactory (org.springframework.beans.factory.support)
preInstantiateSingletons:854, DefaultListableBeanFactory (org.springframework.beans.factory.support)
finishBeanFactoryInitialization:889, AbstractApplicationContext (org.springframework.context.support)
refresh:553, AbstractApplicationContext (org.springframework.context.support)
main:9, AnnotationConfigApplication (com.tbryant.springtest.demo)

第三至八次调用Bean后置处理器入口
	protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
			throws BeanCreationException {

		// Instantiate the bean.
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
			// 实例化Bean,内部第二次调用后置处理器
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		final 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 {
					// 第三次调用后置处理器
					// 把需要注入的属性值从BeanDefinition里取出来存到map中
					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 " +
								"'getBeanNamesOfType' 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;
	}
CommonAnnotationBeanPostProcessor.postProcessMergedBeanDefinition
	public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
		super.postProcessMergedBeanDefinition(beanDefinition, beanType, beanName);
		// 查找@Resource注解的属性
		InjectionMetadata metadata = findResourceMetadata(beanName, beanType, null);
		metadata.checkConfigMembers(beanDefinition);
	}
AutowiredAnnotationBeanPostProcessor.postProcessMergedBeanDefinition
	public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
		// 查找@Autowired注解的属性
		InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
		metadata.checkConfigMembers(beanDefinition);
	}
ApplicationListenerDetector.postProcessMergedBeanDefinition
	public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
		// 记录一下该Bean是否为单例
		this.singletonNames.put(beanName, beanDefinition.isSingleton());
	}

第四次调用Bean后置处理器:提前暴露工厂,为了解决循环依赖问题

spring为了解决循环依赖问题,会以lambda形式提前暴露工厂,在属性注入时通过singletonFactory.getObject()拿到需要的对象。

ConfigurationClassPostProcessor.getEarlyBeanReference
	public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
		return bean;
	}
AutowiredAnnotationBeanPostProcessor.getEarlyBeanReference
	public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
		return bean;
	}

第五次调用Bean后置处理器:判断属性是否需要注入

第五次和第六次调用Bean后置处理器调用链

populateBean:1384, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
doCreateBean:600, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBean:517, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
lambda$doGetBean 0 : 328 , A b s t r a c t B e a n F a c t o r y ( o r g . s p r i n g f r a m e w o r k . b e a n s . f a c t o r y . s u p p o r t ) g e t O b j e c t : − 1 , 1908143486 ( o r g . s p r i n g f r a m e w o r k . b e a n s . f a c t o r y . s u p p o r t . A b s t r a c t B e a n F a c t o r y 0:328, AbstractBeanFactory (org.springframework.beans.factory.support) getObject:-1, 1908143486 (org.springframework.beans.factory.support.AbstractBeanFactory 0:328,AbstractBeanFactory(org.springframework.beans.factory.support)getObject:1,1908143486(org.springframework.beans.factory.support.AbstractBeanFactory$Lambda$12)
getSingleton:229, DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
doGetBean:326, AbstractBeanFactory (org.springframework.beans.factory.support)
getBean:200, AbstractBeanFactory (org.springframework.beans.factory.support)
preInstantiateSingletons:854, DefaultListableBeanFactory (org.springframework.beans.factory.support)
finishBeanFactoryInitialization:889, AbstractApplicationContext (org.springframework.context.support)
refresh:553, AbstractApplicationContext (org.springframework.context.support)
main:9, AnnotationConfigApplication (com.tbryant.springtest.demo)

ConfigurationClassPostProcessor.postProcessAfterInstantiation
	public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
		return true;
	}
CommonAnnotationBeanPostProcessor.postProcessAfterInstantiation
	public boolean postProcessAfterInstantiation(Object bean, String beanName) {
		return true;
	}
AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation
	public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
		return true;
	}

第六次调用Bean后置处理器:完成属性注入

ConfigurationClassPostProcessor.postProcessProperties
		public PropertyValues postProcessProperties(@Nullable PropertyValues pvs, Object bean, String beanName) {
			// Inject the BeanFactory before AutowiredAnnotationBeanPostProcessor's
			// postProcessProperties method attempts to autowire other configuration beans.
			// 如果是全配置类,会被CGLib代理,这里才会进
			if (bean instanceof EnhancedConfiguration) {
				((EnhancedConfiguration) bean).setBeanFactory(this.beanFactory);
			}
			return pvs;
		}
CommonAnnotationBeanPostProcessor.postProcessProperties
	public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
		// 查找@Resource注解的属性
		InjectionMetadata metadata = findResourceMetadata(beanName, bean.getClass(), pvs);
		try {
			// 属性注入
			metadata.inject(bean, beanName, pvs);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(beanName, "Injection of resource dependencies failed", ex);
		}
		return pvs;
	}
AutowiredAnnotationBeanPostProcessor.postProcessProperties
	public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
		// 查找@Autowired注解的属性
		InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
		try {
			// 属性注入
			metadata.inject(bean, beanName, pvs);
		}
		catch (BeanCreationException ex) {
			throw ex;
		}
		catch (Throwable ex) {
			throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
		}
		return pvs;
	}

spring完成属性注入的核心代码是field.set(target, getResourceToInject(target, requestingBeanName))。

初始化生命周期回调:执行Aware方法

AbstractAutowireCapableBeanFactory.invokeAwareMethods
	private void invokeAwareMethods(final String beanName, final 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);
			}
		}
	}

该方法处理BeanNameAware、BeanClassLoaderAware、BeanFactoryAware接口。

第七次调用Bean后置处理器:初始化生命周期回调

第七次和第八次调用Bean后置处理器调用链

initializeBean:1808, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
doCreateBean:602, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBean:517, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
lambda$doGetBean 0 : 328 , A b s t r a c t B e a n F a c t o r y ( o r g . s p r i n g f r a m e w o r k . b e a n s . f a c t o r y . s u p p o r t ) g e t O b j e c t : − 1 , 1908143486 ( o r g . s p r i n g f r a m e w o r k . b e a n s . f a c t o r y . s u p p o r t . A b s t r a c t B e a n F a c t o r y 0:328, AbstractBeanFactory (org.springframework.beans.factory.support) getObject:-1, 1908143486 (org.springframework.beans.factory.support.AbstractBeanFactory 0:328,AbstractBeanFactory(org.springframework.beans.factory.support)getObject:1,1908143486(org.springframework.beans.factory.support.AbstractBeanFactory$Lambda$12)
getSingleton:229, DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
doGetBean:326, AbstractBeanFactory (org.springframework.beans.factory.support)
getBean:200, AbstractBeanFactory (org.springframework.beans.factory.support)
preInstantiateSingletons:854, DefaultListableBeanFactory (org.springframework.beans.factory.support)
finishBeanFactoryInitialization:889, AbstractApplicationContext (org.springframework.context.support)
refresh:553, AbstractApplicationContext (org.springframework.context.support)
main:9, AnnotationConfigApplication (com.tbryant.springtest.demo)

ApplicationContextAwareProcessor.postProcessBeforeInitialization
	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 {
			// 执行各种Aware
			invokeAwareInterfaces(bean);
		}

		return bean;
	}

该方法处理EnvironmentAware、EmbeddedValueResolverAware、ResourceLoaderAware、ApplicationEventPublisherAware、MessageSourceAware、ApplicationContextAware接口。

ConfigurationClassPostProcessor.postProcessBeforeInitialization
		public Object postProcessBeforeInitialization(Object bean, String beanName) {
			if (bean instanceof ImportAware) {
				ImportRegistry ir = this.beanFactory.getBean(IMPORT_REGISTRY_BEAN_NAME, ImportRegistry.class);
				AnnotationMetadata importingClass = ir.getImportingClassFor(bean.getClass().getSuperclass().getName());
				if (importingClass != null) {
					((ImportAware) bean).setImportMetadata(importingClass);
				}
			}
			return bean;
		}
PostProcessorRegistrationDelegate.postProcessBeforeInitialization
		public Object postProcessBeforeInitialization(Object bean, String beanName) {
			return bean;
		}
CommonAnnotationBeanPostProcessor.postProcessBeforeInitialization
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
		try {
			// 执行init-method
			metadata.invokeInitMethods(bean, beanName);
		}
		catch (InvocationTargetException ex) {
			throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
		}
		catch (Throwable ex) {
			throw new BeanCreationException(beanName, "Failed to invoke init method", ex);
		}
		return bean;
	}
AutowiredAnnotationBeanPostProcessor.postProcessBeforeInitialization
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}
ApplicationListenerDetector.postProcessBeforeInitialization
	public Object postProcessBeforeInitialization(Object bean, String beanName) {
		return bean;
	}

初始化生命周期回调:InitializingBean

调用AbstractAutowireCapableBeanFactory.invokeInitMethods方法,内部执行InitializingBean.afterPropertiesSet方法。

第八次调用Bean后置处理器:给需要代理的类生成代理

ApplicationContextAwareProcessor.postProcessAfterInitialization
	public Object postProcessAfterInitialization(Object bean, String beanName) {
		return bean;
	}
ConfigurationClassPostProcessor.postProcessAfterInitialization
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}
PostProcessorRegistrationDelegate.postProcessAfterInitialization
		public Object postProcessAfterInitialization(Object bean, String beanName) {
			if (!(bean instanceof BeanPostProcessor) && !isInfrastructureBean(beanName) &&
					this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount) {
				if (logger.isInfoEnabled()) {
					logger.info("Bean '" + beanName + "' of type [" + bean.getClass().getName() +
							"] is not eligible for getting processed by all BeanPostProcessors " +
							"(for example: not eligible for auto-proxying)");
				}
			}
			return bean;
		}
CommonAnnotationBeanPostProcessor.postProcessAfterInitialization
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}
AutowiredAnnotationBeanPostProcessor.postProcessAfterInitialization
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}
ApplicationListenerDetector.postProcessAfterInitialization
	public Object postProcessAfterInitialization(Object bean, String beanName) {
		if (bean instanceof ApplicationListener) {
			// potentially not detected as a listener by getBeanNamesForType retrieval
			Boolean flag = this.singletonNames.get(beanName);
			if (Boolean.TRUE.equals(flag)) {
				// singleton bean (top-level or inner): register on the fly
				this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
			}
			else if (Boolean.FALSE.equals(flag)) {
				if (logger.isWarnEnabled() && !this.applicationContext.containsBean(beanName)) {
					// inner bean with other scope - can't reliably process events
					logger.warn("Inner bean '" + beanName + "' implements ApplicationListener interface " +
							"but is not reachable for event multicasting by its containing ApplicationContext " +
							"because it does not have singleton scope. Only top-level listener beans are allowed " +
							"to be of non-singleton scope.");
				}
				this.singletonNames.remove(beanName);
			}
		}
		return bean;
	}

你可能感兴趣的:(spring)