三Spring-ioc容器--3Bean实例化源码分析
三Spring-ioc容器--3Bean实例化源码分析
3.3.2 Bean实例化过程
在整个bean实例化的过程中,spring主要干了以下几件大事:
1.bean的实例化过程算法;2.IOC依赖注入;3.注解支撑;4.系列BeanPostProcessors的接口执行;5.AOP动态代理构建;
bean的实例化及其三级缓存的执行逻辑,如下:
TAG0 finishBeanFactoryInitialization(beanFactory)
AbstractApplicationContext.refresh—————————->finishBeanFactoryInitialization(beanFactory);
实例化所有剩余的(非lazy-init)单例。
//完成此上下文的 bean 工厂的初始化,初始化所有剩余的单例 bean
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
//……………………省略部分代码
// Instantiate all remaining (non-lazy-init) singletons.
//beanfactory实例化入口方法(实例化所有剩余单例)
beanFactory.preInstantiateSingletons();
}
TAG0 DefaultListableBeanFactory.preInstantiateSingletons()开始实例化流程
@Override
public void preInstantiateSingletons() throws BeansException {
// Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
//在beandefinition注册时,写进去的beanDefinitionNames
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// 触发所有non-lazy的单例bean的初始化
for (String beanName : beanNames) { //0
/**返回一个合并的 RootBeanDefinition,如果指定的 bean 对应于子 bean 定义,则遍历父 bean 定义。
例如:对于父子beandefinition,父为抽象类,子为继承类,此时需要遍历父beandefinition中,获取信息到子bf
*/
//TAG0.1 getMergedLocalBeanDefinition
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//能实例化的bean:非抽象、非延迟加载,且为单例的,才进行实例化
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { //1
/**----------------------------------factorybean的子类的实例化---------------------------------*/
if (isFactoryBean(beanName)) { //2
//初始化和获取factorybean(实例化的核心方法)-----因为加了factorybean的前缀
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) { //3
final FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
//判断factorybean是否需要提前初始化
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
//SmartFactoryBean多了个isEagerInit方法,用来判断factoryBean是否需要急切地初始化
//默认为false,即当在实际访问bean对象时,才会调用getObject对象
//如果为true,为需要急切初始化,则调用getBean初始化
if (isEagerInit) {
getBean(beanName);
}
} //3
}//2
/**-----------------------------------其他bean对象的初始化------------------------------------*/
else {
//TAG1 getBean(beanName)
//初始化和获取bean
getBean(beanName);
}
}// 1
} //0 for循环
// Trigger post-initialization callback for all applicable beans...
for (String beanName : beanNames) { //1
//获取实例bean
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {//2
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
//特殊的SmartInitializingSingleton,提供一个方法,在保证已经创建所有常规单例bean,在实例化之后后调用
smartSingleton.afterSingletonsInstantiated();
}
}//2
}//1
}
TAG0.1 getMergedLocalBeanDefinition
TAG1 getBean(beanName)--doGetBean
AbstractBeanFactory.doGetBean()抽象实例化bean骨架方法
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
//返回指定 bean 的一个实例,该实例可以是共享的,也可以是独立的。
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
final String beanName = transformedBeanName(name);
Object bean;
/**从缓存中获取bean实例---检查是否有手动注册过该对象
目的是为了解决循环依赖,只会在scope=singleton时出现,prototype不会出现。
同一个对象,对二次获取时,从二级缓存中拿(缓存从三级上升到二级)
*/
// Eagerly check singleton cache for manually registered singletons.
//TAG1.1 getSingleton(beanName)
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) { //0
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
/**bean完全创建好后,才会触发此方法
该方法是FactoryBean的调用入口
FactoryBean接口的作用*/
//TAG1.2 getObjectForBeanInstance(sharedInstance
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
} //0
else { //0
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
//如果是scope=prototype(多例)直接报错
//多例循环依赖不允许,会导致循环依赖
//TAG1.3 isPrototypeCurrentlyInCreation(beanName)
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
BeanFactory parentBeanFactory = getParentBeanFactory();
/*------如果当前beanfactory中不存在该beanname,且父工厂存在,name从parentBeanFactory中寻找-------*/
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { //1
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
//从父beanFactory中getBean
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
} //1
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try { //1
//包装父子beandefinition成rootbeandefinition
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
//检测返回的beandefinition是否是抽象对象,若是,直接报错
//TAG1.4 checkMergedBeanDefinition
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
//检查当前beandefinition是否存在dependsOn属性,保证当前bean依赖的对象,在此beandefinition之前被创建
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) { //2
for (String dep : dependsOn) { //3
//检测是否循环依赖
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
//注册依赖的bean对象
//TAG1.5 registerDependentBean(dep
registerDependentBean(dep, beanName);
try {
//实例化依赖的bean(递归地实例化,保证了先实例化依赖的bean)----》递归的思路
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
} //3
} //2
// Create bean instance.创建单例型的bean实例(对单例beandefinition进行实例化)
//TAG1.6 getSingleton(beanName,ObjectFactory)
if (mbd.isSingleton()) { //2
sharedInstance = getSingleton(beanName, () -> {
try {
//TAG1.6.1 createBean(beanName,)
//传入匿名类FactoryObject,其中方法getObject为createBean(),这是实例化bean的核心方法
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
} //2
//创建多例的bean实例,即scope=prototype类型,该默认类型默认使用延迟加载bean
else if (mbd.isPrototype()) { //2
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
//创建前,处理
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
//创建后,处理
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
} //2
//除prototype,singleton之外的其他作用域
//servlet容器中的bean实例化,会走这里,主要处理scope=session/reequest场景,还有自定义的scope等
else { //2
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
} //2
} //1
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
} //0
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
TAG1.1 getSingleton(beanName)
DefaultSingletonBeanRegistry.getSingleton(beanName)获取三个级别缓存的流程
public Object getSingleton(String beanName) {
return getSingleton(beanName, true);
}
//解决bean循环依赖
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
//根据beanName从一级缓存中获取bean实例--
Object singletonObject = this.singletonObjects.get(beanName);
//当bean对象正在被创建,未被di依赖注入
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
//
synchronized (this.singletonObjects) {
//二级缓存中获取bean
singletonObject = this.earlySingletonObjects.get(beanName);
//如果二级缓存中没有,允许提前暴露,使得bean可以被引用(reference)
if (singletonObject == null && allowEarlyReference) {
//从三级缓存中获取bean-----单例工厂的map中获取单例工厂
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
//从单例工厂拿对象
singletonObject = singletonFactory.getObject();
//设置二级缓存
this.earlySingletonObjects.put(beanName, singletonObject);
//移除三级缓存
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
TAG1.2 getObjectForBeanInstance(sharedInstance--FactoryBean
返回factorybean中定义的对象实例,getObjectForBeanInstance()
//获取给定 bean 实例的对象,bean 实例本身或其创建的对象(如果是 FactoryBean)
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
// Don't let calling code try to dereference the factory if the bean isn't a factory.
if (BeanFactoryUtils.isFactoryDereference(name)) {
if (beanInstance instanceof NullBean) {
return beanInstance;
}
if (!(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
}
if (mbd != null) {
mbd.isFactoryBean = true;
}
return beanInstance;
}
// Now we have the bean instance, which may be a normal bean or a FactoryBean.
// If it's a FactoryBean, we use it to create a bean instance, unless the
// caller actually wants a reference to the factory.
//若不是实现了FactoryBean接口的类,则直接返回原bean
//beanName不是以&靠头,直接返回(不是&开头,表明,不是FactoryBean对象)
if (!(beanInstance instanceof FactoryBean)) {
return beanInstance;
}
Object object = null;
if (mbd != null) {
mbd.isFactoryBean = true;
}
else {
//从factoryBeanObjectCache中获取bean对象(也就是FactoryBean接口中返回的对象,就缓存于此集合
object = getCachedObjectForFactoryBean(beanName);
}
//若缓存factoryBeanobjectCache中没有,则将beanInstance转换成FactoryBean对象后单独缓存
if (object == null) {
// Return bean instance from factory.
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
// Caches object obtained from FactoryBean if it is a singleton.
if (mbd == null && containsBeanDefinition(beanName)) {
//TAG1.2.0 getMergedLocalBeanDefinition
mbd = getMergedLocalBeanDefinition(beanName);
}
boolean synthetic = (mbd != null && mbd.isSynthetic());
//转换后返回对应的bean
//TAG1.2.1 getObjectFromFactoryBean
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
TAG1.2.0 getMergedLocalBeanDefinition
TAG1.2.1 getObjectFromFactoryBean
//从给定的 FactoryBean 中获取要公开的对象
protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
if (factory.isSingleton() && containsSingleton(beanName)) {
synchronized (getSingletonMutex()) {
//从factoryBeanObjectCache中获取bean对象(也就是FactoryBean接口中返回的对象,就缓存于此集合
Object object = this.factoryBeanObjectCache.get(beanName);
if (object == null) {
object = doGetObjectFromFactoryBean(factory, beanName);
// Only post-process and store if not put there already during getObject() call above
// (e.g. because of circular reference processing triggered by custom getBean calls)
Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
if (alreadyThere != null) {
object = alreadyThere;
}
else {
if (shouldPostProcess) {
if (isSingletonCurrentlyInCreation(beanName)) {
// Temporarily return non-post-processed object, not storing it yet..
return object;
}
beforeSingletonCreation(beanName);
try {
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName,
"Post-processing of FactoryBean's singleton object failed", ex);
}
finally {
afterSingletonCreation(beanName);
}
}
if (containsSingleton(beanName)) {
this.factoryBeanObjectCache.put(beanName, object);
}
}
}
return object;
}
}
else {
Object object = doGetObjectFromFactoryBean(factory, beanName);
if (shouldPostProcess) {
try {
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
}
}
return object;
}
}
TAG1.3 isPrototypeCurrentlyInCreation(beanName)
多例情况(scope=ProtoType),有循环依赖直接抛出异常
AbstractBeanFactory.isPrototypeCurrentlyInCreation
protected boolean isPrototypeCurrentlyInCreation(String beanName) {
Object curVal = this.prototypesCurrentlyInCreation.get();
//判断bean是否存在于正在创建中的prototype的map中
return (curVal != null &&
(curVal.equals(beanName) || (curVal instanceof Set && ((Set<?>) curVal).contains(beanName))));
}
TAG1.4 checkMergedBeanDefinition
检查beandefinition是否是抽象对象abstract
AbstractBeanFactory.checkMergedBeanDefinition
protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName, @Nullable Object[] args)
throws BeanDefinitionStoreException {
//如果是abstract,则抛出异常
if (mbd.isAbstract()) {
throw new BeanIsAbstractException(beanName);
}
}
TAG1.5 registerDependentBean(dep
DefaultSingletonBeanRegistry.registerDependentBean
缓存依赖的depend的bean对象,将dependent的beanname存入dependentBeanMap中(hashset结构,key为待创建的beanname,set为该bean依赖对象的集合set)
public void registerDependentBean(String beanName, String dependentBeanName) {
String canonicalName = canonicalName(beanName);
//dependentBeanMap为<bean,set<dependentBeanNames>>,这里存储的是,bean,以及其依赖对象名称的set
synchronized (this.dependentBeanMap) {
Set<String> dependentBeans =
this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet<>(8));
if (!dependentBeans.add(dependentBeanName)) {
return;
}
}
//dependenciesForBeanMap为<dependentbean,set<beanname>>,存储dependbean,以及依赖于其的bean的set
synchronized (this.dependenciesForBeanMap) {
Set<String> dependenciesForBean =
this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new LinkedHashSet<>(8));
dependenciesForBean.add(canonicalName);
}
}
TAG1.6 getSingleton(beanName,ObjectFactory)
创建并缓存单例bean实例
DefaultSingletonBeanRegistry.getSingleton(String beanName, ObjectFactory<?> singletonFactory)
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) { //0
//从一级缓存中获取
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) { //1
//获取单例bean前置处理,是否多次创建,若是直接抛出异常
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
//调用lambda实现,调用createBean,真正创建bean对象
//TAG1.6.1 getObject(createBean())
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
//获取单例bean的后置处理:从正在创建的set集合中,bean创建后移除对应的beanname
afterSingletonCreation(beanName);
}
if (newSingleton) {
//TAG1.6.2 addSingleton(beanName, singletonObject)
//当实例化和初始化完成后,将singleton的bean存入一级缓存,同时把二级缓存和三级缓存remove掉
addSingleton(beanName, singletonObject);
}
} //1
return singletonObject;
} //0
}
TAG1.6.2 addSingleton(beanName, singletonObject)
DefaultSingletonBeanRegistry.addSingleton(String beanName, Object singletonObject)
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
//添加一级缓存
this.singletonObjects.put(beanName, singletonObject);
//移除三级缓存
this.singletonFactories.remove(beanName);
//移除二级缓存
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
TAG1.6.1 getObject(createBean())
lambda调用objectFactory.getObject,然后调用create方法,创建bean
AbstractBeanFactory.createBean
//具体实现由实现类完成
protected abstract Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException;
}
AbstractAutowireCapableBeanFactory. createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
该类的核心方法:1 创建bean实例,2 填充bean实例,3 应用postProcessors
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
// Make sure bean class is actually resolved at this point, and
// clone the bean definition in case of a dynamically resolved Class
// which cannot be stored in the shared merged bean definition.
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
//设置当前RootBeanDefinition的class类型
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
try {
//遍历beandefinition,检测构造方法是否有重载
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.
//调用并返回自己的实例化的对象
//后置处理器BeanPostProcessors有机会返回一个proxy对象,而不是一个需要操作的目标对象
/**
该处是TargetSource接口的运用,可以用一个类实现该接口,然后定义:实例化该对象的方式,该方式不用spring
可以直接返回实例本身
如:@bean,<factory-method>
*/
//TAG1.6.1.0 resolveBeforeInstantiation
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
//可在这里生成代理对象,如果不为null,直接返回
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
//TAG1.6.1.1 doCreateBean
//实例化bean的核心算法
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
}
实例化前阶段
TAG1.6.1.0 resolveBeforeInstantiation(1PP)
第一次postprocessor后置处理器处理。
AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation
这里是第一次调用bean的后置处理器——InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation。
AbstractAutowireCapableBeanFactory
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
//如果mbd被标记为,在实例化前需要处理(beforeInstantiationResolved==true)
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) { //0
// Make sure bean class is actually resolved at this point.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { //1
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) { //2
//调用实例化前后置处理方法
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
} //2
}// 1
mbd.beforeInstantiationResolved = (bean != null);
} //0
//当mbd实例化之前,不需要被处理,就直接返回bean
return bean;
}
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName)
throws BeansException {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
//遍历bpp,找到InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation执行
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
return null;
}
此处,就是判断当前rootbeandefinition是否需要提前处理。如果需要,就寻找找到InstantiationAwareBeanPostProcessor,执行其postProcessBeforeInstantiation()方法。
通常用来在实例化一个bean前,创建一个代理类proxy返回。然后,后续的实例化、初始化过程,就不再执行。
beforeInstantiate方法,通常实现类是AbstractAutoProxyCreator.postProcessBeforeInstantiation,判断当前beandefinition是否需要被代理,需要就创建代理类,并存入map内。
从类继承结构,看出这个bean后置处理器,通常调用postProcessBeforeInstantiation,在实力话之前,根据需要创建proxy代理类。
TAG1.6.1.1 doCreateBean
AbstractAutowireCapableBeanFactory.doCreateBean————实例化bean的核心算法
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.实例化bean
//BeanWrapper封装的是bean的实例
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
//移除beanWrapper缓存对象
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//DCB1 createBeanInstance--实例化
//当缓存中没有BeanWrapper,通过反射创建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 {
//对类中注解的装配过程
//DCB2 applyMergedBeanDefinitionPostProcessors--AOP
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.
//单例bean提前暴露,解决循环依赖问题
//(提前暴露条件:mbd单例&允许循环依赖&单例正在创建中)
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");
}
//提前暴露时,添加三级缓存(循环依赖)
//DCB3 addSingletonFactory(name,objectFactory)
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
/** -------------------------Initialize the bean instance.-----------------------------*/
Object exposedObject = bean;
try {
//DCB4 populateBean--属性赋值(IOC)
//bean的依赖对象的注入,核心方法——ioc
populateBean(beanName, mbd, instanceWrapper);
//bean实例化+ioc依赖注入完成后调用,aop入口在此
//bean实例化后置处理
//DCB5 initializeBean--初始化
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);
}
}
}
}
}
// Register bean as disposable.
try {
//注册bean销毁接口,给外部servlet容器调用,用来销毁bean
//DCB6 registerDisposableBeanIfNecessary
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
实例化阶段
DCB1 createBeanInstance-实例化
AbstractAutowireCapableBeanFactory.createBeanInstance—------反射创建bean实例
//args为实例化bean的构造函数的参数列表
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);
//确保class不为空,且访问权是public
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方式实例化---------目前该实例化过程,被spring遗弃-------------------*/
// 判断当前beanDefinition中是否包含实例供应器,此处相当于一个回调方法,利用回调方法来创建bean
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
/**--------判断definition中是否有factoryMethod属性-------工厂方法factory-method创建bean实例策略-----------*/
if (mbd.getFactoryMethodName() != null) {
//触发factoryMethod抽象方法调用
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
/**-------------------------已经创建过相同的bean时,实例化逻辑----------------------------*/
// Shortcut when re-creating the same bean...
/** 策略: 一个类可能有多个构造器,所以Spring得根据参数个数、类型确定需要调用的构造器;
在使用构造器创建实例后,Spring会将解析过后确定下来的构造器或工厂方法保存在缓存中,避免再次创建相同bean时再次解析*/
//标记bean是否被处理过,防止重复创建同一个bean
boolean resolved = false;
//是否需要autowire
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);
}
}
/**----------------------------------根据参数args解析,确定构造函数----------------------------------*/
// Candidate constructors for autowiring?
//获取当前bean后置处理器中有@autowired注解的构造函数constructor对象集合(有参)
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
//若构造函数有注解,则自动装配构造函数(传入实参,引用类型则触发获取bean的操作)
return autowireConstructor(beanName, mbd, ctors, args);
}
//DCB1.1 instantiateBean(无参)
//无参构造bean的实例化(直接实例化返回bean)--默认;如果没有无参构函且有多个无@autowire的构函,会报错
// No special handling: simply use no-arg constructor.
return instantiateBean(beanName, mbd);
}
从上面实例化实例化bean的流程看出,实例化共有如下几种方式。
DCB1.1 instantiateBean
AbstractAutowireCapableBeanFactory.instantiateBean——用默认无参构造函数来实例化该bean
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
try {
Object beanInstance;
final BeanFactory parent = this;
if (System.getSecurityManager() != null) {
//获取实例化策略,然后调用instantiate来实例化
beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
getInstantiationStrategy().instantiate(mbd, beanName, parent),
getAccessControlContext());
}
else {
//DCB1.1.0 getInstantiationStrategy()
//DCB1.1.1 SimpleInstantiationStrategy.instantiate
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
}
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
}
}
DCB1.1.0 getInstantiationStrategy()
实例化策略:
默认采用cglib策略。上面的实例化策略类,共提供了如下几种策略:
1 InstantiationStrategy
对于实例化策略接口InstantiationStragety,提供了三个同名方法instantiate,分别是无参构函、指定构造器、指定factorymethod的实例化。
public interface InstantiationStrategy {
//无参构造,实例化
Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner)
throws BeansException;
//通过指定的构造器ctor,实例化bean
Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner,
Constructor<?> ctor, Object... args) throws BeansException;
//通过指定的factoryMethod,实例化bean
Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner,
Object factoryBean, Method factoryMethod, Object... args) throws BeansException;
}
2 SimpleInstantiationStrategy
DCB1.1.1 SimpleInstantiationStrategy.instantiate
提供了三种实例化策略,这里以无参构造函数来实例化bean为例。
public class SimpleInstantiationStrategy implements InstantiationStrategy {
//此处仅以无参构造函数,实例化bean为例
@Override
public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {
/**------------------bean中没有有需要override的方法,用默认流程实例化bean------------------------------ */
// Don't override the class with CGLIB if no overrides.
//(---bd.getMethodOverrides()方法,返回ioc容器需要重写的方法---)
//检查rootbeandefinition中是否有需要override的方法,如果没有,就不用cglib构造bean,直接用下述流程实例化bean
if (bd.getMethodOverrides().isEmpty()) { //0
Constructor<?> constructorToUse;
synchronized (bd.constructorArgumentLock) { //1
//结合DCB1 createBeanInstance
//由于实例化bean之前,解析构造函数、factorymethod的过程复杂,因此,为了方便创建同一个bean,会对解析出来的(resolved)cons和factorymethod,缓存入rootbeandefinition中,方便下次直接获取,而不用再解析
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
/** ---------------如果beandefinition未被解析过,没有缓存过cons和factorymethod-----------------------*/
if (constructorToUse == null) { //2
final Class<?> clazz = bd.getBeanClass();
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try { //3
if (System.getSecurityManager() != null) {
constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {
@Override
public Constructor<?> run() throws Exception {
return clazz.getDeclaredConstructor((Class[]) null);
}
});
}
else {
//解析并获取构函
constructorToUse = clazz.getDeclaredConstructor((Class[]) null);
}
//缓存bd解析过得构函
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Exception ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
} //3
} //2
} //1
//DCB1.1.1.1 instantiateClass
/** ---------------如果beandefinition被解析过,使用缓存的constructor实例化bean-----------------------*/
return BeanUtils.instantiateClass(constructorToUse);
} //0
/**-------------------------------bean中有需要override的方法,用cglib构造------------------------------- */
else {
//DCB1.1.1.2 instantiateWithMethodInjection
// Must generate CGLIB subclass.
//该方法由子类CglibSubclassingInstantiationStrategy实现
return instantiateWithMethodInjection(bd, beanName, owner);
}
}
/** ---------------------------提供两种动态代理,实例化对象。由cdlib的子类实现--------------------------------*/
//由子类实现,使用无参构造函数
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, String beanName, BeanFactory owner) {
throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
}
//由子类实现,使用给定ctor以及参数args,实例化对象
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, String beanName, BeanFactory owner,
Constructor<?> ctor, Object... args) {
throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
}
SimpleInstantiationStrategy提供了另外两种方法,通过动态代理策略,来实例化bean。
3 CglibSubclassingInstantiationStrategy
public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationStrategy {
//无参构造器实例化
@Override
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, String beanName, BeanFactory owner) {
return instantiateWithMethodInjection(bd, beanName, owner, null);
}
//有参构造器,实例化
@Override
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, String beanName, BeanFactory owner,
Constructor<?> ctor, Object... args) {
// Must generate CGLIB subclass...
return new CglibSubclassCreator(bd, owner).instantiate(ctor, args);
}
//cglibstratety内部类
private static class CglibSubclassCreator { //0
public Object instantiate(Constructor<?> ctor, Object... args) { //1
//cglib创建增强子类
Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
Object instance;
/**----------------如果无构造函数,用cglib增强过的class类,反射创建bean----------------------*/
if (ctor == null) {
instance = BeanUtils.instantiate(subclass);
}
/**-----------------------------如果有构造函数----------------------------*/
else {
try {
//根据传入ctor参数类型,获取增强后的subclass对应的构造函数
Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
//根据构造函数ctor,反射创建实例
instance = enhancedSubclassConstructor.newInstance(args);
}
catch (Exception ex) {
throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
"Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex);
}
}
// SPR-10785: set callbacks directly on the instance instead of in the
// enhanced class (via the Enhancer) in order to avoid memory leaks.
Factory factory = (Factory) instance;
factory.setCallbacks(new Callback[] {NoOp.INSTANCE,
new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
return instance;
} //1
//cglib方法,根据给定beandefinition,创建增强的子类
private Class<?> createEnhancedSubclass(RootBeanDefinition beanDefinition) { //1
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(beanDefinition.getBeanClass());
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
if (this.owner instanceof ConfigurableBeanFactory) {
ClassLoader cl = ((ConfigurableBeanFactory) this.owner).getBeanClassLoader();
enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(cl));
}
enhancer.setCallbackFilter(new MethodOverrideCallbackFilter(beanDefinition));
enhancer.setCallbackTypes(CALLBACK_TYPES);
return enhancer.createClass();
} //1
} //0
cglib实例化策略,首先创建增强的Class对象,然后根据实例化传入参数,是否有构造函数ctor,确定具体的实例化策略:如果无ctor,调用BeanUtils.instantiate(subclass),根据class对象,实例化bean;如果有ctor,获取增强后对应的构造函数,然后再通过构造函数,反射创建实例bean。
DCB1.1.1 Strategy.instantiate总结
在DCB1.1 instantiateBean中,实例化bean方法
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
总结上述流程:
首先,获取实例化策略
然后,执行startegy.instantiate方法
首先,在SimpleInstantiationStrategy.instantiate中,首先根据是否有ctor、factorymethod,来执行对应的实例化策略。以无参构造实例为例————
1 判断bd中是否有需要IOC容器重写的override方法
1.1 没有需要重写的方法---判断bd是否缓存解析过同一bean的ctro或者factorymethod
1.1.1 若未缓存:从rootbeandefinition中获取ctor
然后根据ctor,实例化 instantiateClass(Constructor<T> ctor, Object... args)
1.2 有需要重写override的方法,调用cglib的实例化策略:
1.2.1 createEnhancedSubclass --cglib方法,创建增强的新的subclass子类
1.2.2 如果传入参数无构造函数,用instance = BeanUtils.instantiate(subclass),根据class类,实例化;
1.2.3 如果传入参数有ctor,通过subclass的构造函数,反射创建bean实例
//根据传入ctor参数类型,获取增强后的subclass对应的构造函数
Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
//根据构造函数ctor,反射创建实例
instance = enhancedSubclassConstructor.newInstance(args);
DCB1.1.1.1 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);
if (KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(ctor.getDeclaringClass())) {
return KotlinDelegate.instantiateClass(ctor, args);
}
else {
//获取构造函数参数类型
Class<?>[] parameterTypes = ctor.getParameterTypes();
Assert.isTrue(args.length <= parameterTypes.length, "Can't specify more arguments than constructor parameters");
Object[] argsWithDefaultValues = new Object[args.length];
for (int i = 0 ; i < args.length; i++) {
if (args[i] == null) {
Class<?> parameterType = parameterTypes[i];
argsWithDefaultValues[i] = (parameterType.isPrimitive() ? DEFAULT_TYPE_VALUES.get(parameterType) : null);
}
else {
argsWithDefaultValues[i] = args[i];
}
}
//构造函数反射创建bean
return ctor.newInstance(argsWithDefaultValues);
}
}
DCB1.1.1.2 instantiateWithMethodInjection
可详细看DCB1.1.0。这里的方法,需要
DCB2 applyMergedBeanDefinitionPostProcessors--AOP(3pp)
AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors
将 MergedBeanDefinitionPostProcessors 应用于指定的 bean 定义,调用它们的 {@code postProcessMergedBeanDefinition} 方法。
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
//循环调用MergedBeanDefinitionPostProcessor,实现父子类bd的后置处理
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
MergedBeanDefinitionPostProcessor的子类有CommonAnnotationBeanProcessor和AutuwiredAnnotationBeanPostProcessor,调用postProcessMergedBeanDefinition方法,处理合并的beandefinition。
1 AutowiredAnnotationBeanPostProcessor 处理@Autowired和@Value注解bean定义信息
2 CommonAnnotationBeanPostProcessor 处理@Resource、@PostConstruct、@PreDestroy注解的bean定义信息
注意:
这里只是解析注解,并没有进行赋值操作。applyMergedBeanDefinitionPostProcessors就是解析对应注解标注的属性和方法,解析完之后返回元数据信息metadata,然后放到缓存中,下次使用的时候直接获取。
如果xml中配置了,注解也标注了,那么默认会丢弃掉注解的配置,也就是xml配置优先级比较高**
DCB2.1 AutowiredAnnotationBeanPostProcessor.postProcessMergedBeanDefinition
AutowiredAnnotationBeanPostProcessor
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
if (beanType != null) {
//找出所有需要完成注入的“点”-----@Autowired @Value注解方法或者属性,获取注解的元数据metadata
InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
//复制InjectionMetadata.injectedElements到this.checkedElements
metadata.checkConfigMembers(beanDefinition);
}
}
DCB2.2 CommonAnnotationBeanPostProcessor.postProcessMergedBeanDefinition
CommonAnnotationBeanPostProcessor
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
//解析@PostConstruct与@PreDestroy,并封装到Metadata中,把Metadata放到lifecycleMetadataCache
super.postProcessMergedBeanDefinition(beanDefinition, beanType, beanName);
if (beanType != null) {
//找出所有需要完成注入的“点”-----@Resource注解
InjectionMetadata metadata = findResourceMetadata(beanName, beanType, null);
metadata.checkConfigMembers(beanDefinition);
}
}
InitDestroyAnnotationBeanPostProcessor
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
if (beanType != null) {
//找到bean声明周期的方法--初始化、销毁
LifecycleMetadata metadata = findLifecycleMetadata(beanType);
//复制InjectionMetadata.injectedElements到this.checkedElements
metadata.checkConfigMembers(beanDefinition);
}
}
DCB3 addSingletonFactory(name,objectFactory)-(getEarlyBeanReference--4pp)
如果允许提前暴漏bean(提前暴露条件:mbd单例&允许循环依赖&单例正在创建中),会提前暴漏工厂类ObjectFactory,来解决循环依赖。这个工厂,在出现循环依赖的时候执行。
DefaultSingletonBeanRegistry.addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
将工厂类加入三级缓存中,同时移除二级缓存。
引入匿名创建工厂类ObjectFactory的作用:创建匿名类ObjectFactory,是为了防止循环引用,而尽早的持有对象的引用。这里暴露的是工厂,而不是对象,在解决循环依赖时,可以ObjectFactory.getObject来获取真实对象。
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
if (!this.singletonObjects.containsKey(beanName)) {
//添加三级缓存
this.singletonFactories.put(beanName, singletonFactory);
//移除老的二级缓存对象
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
}
DCB3.1 getEarlyBeanReference(4PP)
当后续调用三级缓存ObjectFactory.getObject——getEarlyBeanReference,会调用提前暴露方法,
AbstractAutowireCapableBeanFactory.getEarlyBeanReference
AbstractAutowireCapableBeanFactory
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
if (bean != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
//寻找SmartInstantiationAwareBeanPostProcessor
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
//执行getEarlyBeanReference获取实例对象
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
if (exposedObject == null) {
return exposedObject;
}
}
}
}
return exposedObject;
}
针对后置处理器SmartInstantiationAwareBeanPostProcessor,
实现类为AbstractAutoProxyCreator
AbstractAutoProxyCreator
public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
//判断当前bean是否是factorybean,如果是,返回前者本身;否则,
Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
//判断AbstractAutoProxyCreator.earlyProxyReferences中是否缓存有cacheKey对象
if (!this.earlyProxyReferences.contains(cacheKey)) {
this.earlyProxyReferences.add(cacheKey);
}
//如果有需要,包装原始bean,例如该bean需要被代理proxy
return this.wrapIfNecessary(bean, beanName, cacheKey);
}
protected Object getCacheKey(Class<?> beanClass, String beanName) {
if (StringUtils.hasLength(beanName)) {
//判断当前beanclass是否是factoryBean.class,如果是,需要&beanname,这样获取的是factorybean本身
return FactoryBean.class.isAssignableFrom(beanClass) ? "&" + beanName : beanName;
} else {
return beanClass;
}
}
DCB4 populateBean--属性赋值(ioc)
AbstractAutowireCapableBeanFactory
//用来自rootbeandefinition内的属性,填充BeanWrapper中的bean的属性
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {
if (!pvs.isEmpty()) {
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.
boolean continueWithPropertyPopulation = true;
/** -------------------------属性填充前,最后修改bean的时机------------------------*/
//DCB4.1 InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation
// 如果存在InstantiationAwareBeanPostPricessor后置处理器,则依次调用其postProcessAfterInstantiation()方法
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
// 在设置属性之前,任何InstantiationAwareBeanPostPricessor后置处理器都有机会去修改Bean
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
//决定程序是否继续进行属性填充。只要有一个 InstantiationAwareBeanPostProcessor 返回false,都会终止属性填充的过程
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
//如果有一个InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation方法执行,返回false,就不再执行后续属性填充过程,直接返回
if (!continueWithPropertyPopulation) {
return;
}
/** ---------------------------xml配置的bean的autowiring自动装配-------------------------------*/
//获取beandefinition内的属性
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
//DCB4.2 autowireByName
//处理bean的autowire的类型,有byname、no、bytype、constructor等
// 默认是AUTOWIRE_NO,因此不会走下面的autowireByName、autowireByType方法,
// 需要xml显式配置,如autowire="byType"
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) { //1
//如果需要autowiring自动注入,将mbd中属性值pvs转换为可变属性值对象MutablePropertyValues
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
//byName模式autowire完成注入
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
//用自动装配autowire后新的配置,覆盖老的配置
pvs = newPvs;
} //1
//判断是否有InstantiationAwareBeanPostProcessor类
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
//检测是否需要依赖检查(目前,rootbeandefinition中的dependencycheck属性已经被弃用)
boolean needsDepCheck = (mbd.getDependencyCheck()!=AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) { //1
//如果不是
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
//获取BeanPostProcessor后置处理器对象
for (BeanPostProcessor bp : getBeanPostProcessors()) { //2
if (bp instanceof InstantiationAwareBeanPostProcessor) { //3
//找到InstantiationAwareBeanPostProcessor后置处理器
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
/**-----------------注解注入(@autowire和@resource的属性注入)---------------------------------- */
//DCB4.3 InstantiationAwareBeanPostProcessor.postProcessProperties
//执行postProcessProperties方法,对配置进行处理————对象属性依赖注入
// CommonAnnotationBeanPostProcessor.postProcessProperties
// AutowiredAnnotationBeanPostProcessor.postProcessProperties
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) { //4
if (filteredPds == null) {
//过滤需要进行依赖检查的属性描述符
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
//DCB4.4 InstantiationAwareBeanPostProcessor.postProcessPropertyValues
//新版本spring中,该方法已经陪遗弃
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
} //4
pvs = pvsToUse;
} //3
} //2
}//1
if (needsDepCheck) { //1
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
checkDependencies(beanName, mbd, filteredPds, pvs);
} //1
/**------------------------------填充xml中属性-------------------------------------- */
if (pvs != null) {
//DCB4.5 applyPropertyValues
//填充属性值(填充xml中配置的属性---xml配置属性优先于注解配置的属性)
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
populateBean中,调用了InstantiationAwareBeanPostProcessor的相关方法。
其实现类主要有CommonAnnotationBeanPostProcessor、AutowireAnnotationBeanPostProcessor、AbstractAutoProxyCreator等。
实例化后阶段
DCB4.1 InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation(5pp)
/** -------------------------属性填充前,最后修改bean的时机------------------------*/
//DCB4.1 InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation
// 如果存在InstantiationAwareBeanPostPricessor后置处理器,则依次调用其postProcessAfterInstantiation()方法
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
// 在设置属性之前,任何InstantiationAwareBeanPostPricessor后置处理器都有机会去修改Bean
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
//决定程序是否继续进行属性填充。只要有一个 InstantiationAwareBeanPostProcessor 返回false,都会终止属性填充的过程
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
//如果有一个InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation方法执行,返回false,就不再执行后续属性填充过程,直接返回
if (!continueWithPropertyPopulation) {
return;
}
属性进行填充前,执行postProcessAfterInstantiation。如果返回false,不再执行后续的populate属性填充的过程,直接返回。
这个方法默认返回true。
InstantiationAwareBeanPostProcessor
default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
return true;
}