spring中用一句getBean就能取出一个实例化好的bean,这个bean是属于IOC容器管理的,下面是源码大致流程图:
?
?1、getBean 源码流程
一、入口 getBean和真正做事的doGetBean:
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
protected <T> T doGetBean(final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {
//beanName转换,这里主要有两方面的考虑:
//1:如果beanName是以&开头的,则表明是要返回FactoryBean本身,而不是其生产出来的对象,而FactoryBean存储的时候,跟普通的bean一样
//2:如果传入的是别名,则是需要转换为实际的beanName的
final String beanName = transformedBeanName(name);
Object bean;
// 先尝试从缓存中获取Bean实例,这个位置就是三级缓存解决循环依赖的方法
Object sharedInstance = getSingleton(beanName);
//不为空则表明之前被创建过
if (sharedInstance != null && args == null) {
if (logger.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
// 1. 如果 sharedInstance 是普通的 Bean 实例,则下面的方法会直接返回
// 2. 如果 sharedInstance 是工厂Bean类型,则需要获取 getObject 方法,可以参考关于 FactoryBean 的实现类
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// 循环依赖有三种,setter注入、多实例和构造函数,Spring 只能解决 setter 注入,所以这里是 Prototype 则会抛出异常
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// 查看父类中是否有相关的bean的定义信息
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// 获取 name 对应的 beanName,如果 name 是以 & 开头,则返回 & + beanName
String nameToLookup = originalBeanName(name);
//递归去父类中查找
if (args != null) {
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
if (!typeCheckOnly) {
//标记当前bean 已经创建完或者是正在进行创建防止出现重复创建
markBeanAsCreated(beanName);
}
try {
// 将父类的定义的BeanDefinition与子类的BeanDefinition进行合并覆盖
// spring希望处理bean的定义能统一,很多bean定义是不同的子类实现类,而且可能被处理器修改,所以就需要在访问bean定义的时候进行合并
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// 检查当前创建的 bean 定义是否为抽象 bean 定义
checkMergedBeanDefinition(mbd, beanName, args);
// 处理使用了 depends-on 注解的依赖创建 bean 实例
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
// 监测是否存在 depends-on 循环依赖,若存在则会抛出异常
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
// 注册依赖记录
registerDependentBean(dep, beanName);
try {
// 加载 depends-on 依赖(dep 是 depends-on 缩写)
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// 创建单例 bean 实例
if (mbd.isSingleton()) {
// 把 beanName 和 new ObjectFactory 匿名内部类传入回调
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
// 创建 bean
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// 创建失败则销毁
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
// 创建其他类型的 bean 实例
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
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, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// 如果需要类型转换,这里会进行操作
if (requiredType != null && bean != null && !requiredType.isInstance(bean)) {
try {
return getTypeConverter().convertIfNecessary(bean, requiredType);
}
catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
// 返回 Bean
return (T) bean;
}
二、getSingleton:从缓存中获取bean
因为doGetBean有很多地方会调用,可能当前调用的时候缓存里已经有bean存在了
public Object getSingleton(String beanName) {
return getSingleton(beanName, true);
}
//判断是否有缓存起来的bean
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
//singletonObjects一级缓存(单例缓存池)中去获取对象,保存的为实例化并赋值过的bean,可以直接使用
Object singletonObject = this.singletonObjects.get(beanName);
// 若在第一级缓存中没有获取到对象,并且singletonsCurrentlyInCreation正在创建的单实例的list包含该beanName
// Spring IoC容器初始化加载单实例bean的时候第一次进来的时候 该list中一般返回空,但是循环依赖的时候可以满足该条件
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
// 尝试去二级缓存中获取对象(二级缓存中的对象是一个早期对象)
// 何为早期对象:就是bean刚刚调用了构造方法,还没给bean的属性进行赋值的对象就是早期对象
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
//直接从三级缓存中获取ObjectFactory对象 这个对象就是用来解决循环依赖的关键所在
//在getBean的过程中,当bean调用了构造方法的时候,把早期对象包裹成一个ObjectFactory暴露到三级缓存中
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
三、getObjectForBeanInstance:FactoryBean 中获取 bean 实例
protected Object getObjectForBeanInstance(Object beanInstance, String name, String beanName, RootBeanDefinition mbd) {
//如果name是以&开头的 但是不是FactoryBean,则直接抛出异常
if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
}
// beanInstance可能是一个普通的bean,也可能是一个FactoryBean
// 如果是一个普通的bean,则直接返回
if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
return beanInstance;
}
//FactoryBean创建出bean实例返回
Object object = null;
// 如果 mbd 为空,则从缓存加载 bean(FactoryBean 生成的单例 bean 实例会缓存到 factoryBeanObjectCache 集合中,方便使用)
if (mbd == null) {
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
if (mbd == null && containsBeanDefinition(beanName)) {
mbd = getMergedLocalBeanDefinition(beanName);
}
boolean synthetic = (mbd != null && mbd.isSynthetic());
// 调用 getObjectFromFactoryBean 获取实例
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
四、另一个?getSingleton:创建单例Bean(重点)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(java.lang.String, org.springframework.beans.factory.ObjectFactory<?>)
?这一部分是使用 beanName 和 singletonFactory 匿名内部类传入等待回调的方式创建单实例 Bean 实例
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
?
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
// 加锁
synchronized (this.singletonObjects) {
// 尝试从单例缓存池中获取对象
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
// 当前这个单例是否正在被销毁,true代表单例已经执行了自身的destroy销毁方法,或者有异常的时候执行了destroySingleton方法等情况
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
/**
* 标记当前的bean马上就要被创建了
* singletonsCurrentlyInCreation 在这里会把beanName加入进来,若第二次循环依赖(构造器注入会抛出异常)
*/
beforeSingletonCreation(beanName);
boolean newSingleton = false;
// this.suppressedExceptions 存放着各种异常信息
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
// 调用从前面传进来的重载的ObjectFactory的getObject(),创建bean
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// 看这个时候单例是否已经被创建了,如果是的话,不报错,继续执行
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
// 把出现过的异常加进去
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
//后置处理主要做的事情就是把singletonsCurrentlyInCreation标记正在创建的bean从集合中移除
afterSingletonCreation(beanName);
}
if (newSingleton) {
//将新创建的bean加入缓存,并且删除加载bean过程中所记录的各种辅助状态
//这些辅助状态主要是在回调方法创建bean时候引入的
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
五、createBean:?创建Bean的singletonFactory.getObject()其实是调用createBean()方法
createBean方法里面还是在做一些准备工作,真正的创建bean交给了doCreateBean
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
//根据指定的BeanDefinition信息 解析bean class 并且存储在BeanDefinition中
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
//对已有的bean definition进行克隆 以防一动态解析的class不能存储在合并的bean definition中
//这里说的动态解析的class是指在bean class的定义中使用EL表达式或者自己定义的beanExpressionResolver
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
try {
// 验证及准备覆盖的方法
mbdToUse.prepareMethodOverrides();
} catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// 调用BeanPostProcessors后置处理器 用来处理创建代理对象的,
// 但是代理对象不再这里创建(因为对象还没有进行实例化)把我们的切面和通知(增强器)进行缓存下来
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
} catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
// 创建bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
} catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
throw ex;
} catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
?真正的创建我们的bean的实例对象的doCreateBean(beanName, mbdToUse, args)的方法
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// BeanWrapper是对Bean的包装,其接口中所定义的功能很简单包括设置获取被包装的对象,获取被包装bean的属性描述器
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
// 从未完成创建的包装bean缓存中清理并获取相关的包装bean实例,单例,不可以重复
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 根据bean对应的策略创建新的实例,如:工厂方法、构造器自动注入、简单初始化
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
// 获取被包装的Bean,后续对bean的改动等于对wrapper进行改动,即对wrapper的改动也会改动bean
final Object bean = instanceWrapper.getWrappedInstance();
// 获取实例化对象的类型
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// 应用MergedBeanDefinitionPostProcessor 后处理器,合并bean的定义信息
// Autowire等注解信息就是在这一步完成预解析,并且将注解需要的信息放入缓存
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
//catch..
mbd.postProcessed = true;
}
}
// 是否需要提前曝光=单例&允许循环依赖&bean正在创建中
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
// 为了避免循环依赖,在bean初始化完成前,就把我们的早期对象包装成一个singletonFactory对象放入工厂缓存(singletonFactories)
// 该对象提供了一个getObject方法,该方法内部调用getEarlyBeanReference方法
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
Object exposedObject = bean;
try {
// 对bean属性进行填充,注入bean中的属性,会递归初始化依赖的bean
populateBean(beanName, mbd, instanceWrapper);
// 调用初始化方法
// 1. 判断是否实现了BeanNameAware、BeanClassLoaderAware、BeanFactoryAware如果有,将相关属性进行传递.
// 2. 调用BeanPostProcessor的前置操作:例如->@PostConstruct
// 3. 调用bean初始化的前置操作,即生命周期回调函数.实现InitializingBean#afterPropertiesSet、具有依赖注入的自定义方法
// 4. 调用BeanPostProcessor的后置操作
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
//catch
if (earlySingletonExposure) {
// 去缓存中获取到我们的对象 由于传递的allowEarlyReference 是false 要求只能在一级二级缓存中去获取
// 如果存在循环依赖,也就是说该bean已经被其他bean递归加载过,放入了提早曝光的bean缓存中
// 正常普通的bean(不存在循环依赖的bean) 创建的过程中,压根不会把三级缓存提升到二级缓存中
Object earlySingletonReference = getSingleton(beanName, false);
//只有检测到循环依赖的情况下,earlySingletonReference不会为null
if (earlySingletonReference != null) {
//如果exposedObject没有在 initializeBean 初始化方法中改变,也就是没有被增强(代理)
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
// 如果上面的判断没通过,则表明引用的bean和注入的bean不一致
// 此时有两个判断条件:
// 1. 在循环引用的情况下是否要求注入原始bean实例,即使注入的bean最终被增强(AOP处理)也是如此.
// 意思就是说,只认原始类型,如果在initializeBean中对bean进行了替换,Spring会认为是异常.
// 2. 当前是否触发了循环依赖: dependentBeanMap记录着每个依赖于此Bean的Bean实例集合
// 当发生循环依赖的时候不允许新创建实例对象
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);
}
}
//因为bean创建后,其依赖的bean一定也是已经创建的
//如果actualDependentBeans不为空,则表示依赖的bean并没有被创建完,即存在循环依赖
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException("...");
}
}
}
}
// 根据scope注册bean
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
//catch...
return exposedObject;
}
?六、createBeanInstance:使用合适的实例化策略来创建新的实例:工厂方法、构造函数自动注入、简单初始化
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// 从bean定义中解析出当前bean的class对象,前面在createBean已经进行过解析了,这里会直接从mbd.getBeanClass()返回
Class<?> beanClass = resolveBeanClass(mbd, beanName);
// 检测类的访问权限。默认情况下,对于非 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<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
// 工厂方法,我们通过配置类来进行配置的话 采用的就是工厂方法
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// 判断当前构造函数是否被解析过
boolean resolved = false;
// 有没有必须进行依赖注入
boolean autowireNecessary = false;
// 通过getBean传入进来的构造函数是否来指定需要推断构造函数
// 若传递进来的args不为空,那么就可以直接选出对应的构造函数
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
// 判断我们的bean定义信息中的resolvedConstructorOrFactoryMethod(用来缓存我们的已经解析的构造函数或者工厂方法)
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
if (autowireNecessary) {
// 通过有参的构造函数进行反射调用
return autowireConstructor(beanName, mbd, null, null);
}
else {
// 调用无参数的构造函数进行创建对象
return instantiateBean(beanName, mbd);
}
}
// 通过bean的后置处理器进行选举出合适的构造函数对象
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
//通过后置处理器解析出构造器对象不为null || 获取bean定义中的注入模式是构造器注入
// || bean定义信息ConstructorArgumentValues || 获取通过getBean的方式传入的构造器函数参数类型不为nul
if (ctors != null ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
// 通过构造函数创建对象
return autowireConstructor(beanName, mbd, ctors, args);
}
// 使用无参数的构造函数调用创建对象
return instantiateBean(beanName, mbd);
}
七、addSingletonFactory 解决循环依赖,把早期对象包装成一个singletonFactory对象放到三级缓存
判断是否暴露早期对象条件满足就暴露早期对象,把我们的早期对象包装成一个singletonFactory对象 该对象提供了一个getObject方法,该方法内部调用getEarlyBeanReference方法
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
//加锁
synchronized (this.singletonObjects) {
//单例缓存池中没有包含当前的bean
if (!this.singletonObjects.containsKey(beanName)) {
//加入到三级缓存中 暴露早期对象用于解决循环依赖
this.singletonFactories.put(beanName, singletonFactory);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
}
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
//判读我们容器中是否有InstantiationAwareBeanPostProcessors类型的后置处理器
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
//获取我们所有的后置处理器
for (BeanPostProcessor bp : getBeanPostProcessors()) {
//判断我们的后置处理器是不是实现了SmartInstantiationAwareBeanPostProcessor接口
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
//进行强制转换
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
//挨个调用SmartInstantiationAwareBeanPostProcessor的getEarlyBeanReference
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
return exposedObject;
}
?八、populateBean:对bean属性进行填充,注入bean中的属性,会递归初始化依赖的bean
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
//若bw为null的话,则说明对象没有实例化
if (bw == null) {
//进入if说明对象有属性,bw为空,不能为他设置属性,那就在下面就执行抛出异常
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
return;
}
}
// 给InstantiationAwareBeanPostProcessors最后一次机会在属性注入前修改Bean的属性值
// 官方的解释是:让用户可以自定义属性注入。比如用户实现一个 InstantiationAwareBeanPostProcessor 类型的后置处理器,
// 并通过postProcessAfterInstantiation 方法向 bean 的成员变量注入自定义的信息。
// InstantiationAwareBeanPostProcessor.postProcessAfterInstantiationM没有进行任何处理,
// 若我们自己实现了这个接口 可以自定义处理.....spring 留给我们自己扩展接口的
// 具体通过调用postProcessAfterInstantiation方法,如果调用返回false,表示不必继续进行依赖注入,直接返回
boolean continueWithPropertyPopulation = true;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 一般情况下,应该是返回true 。
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
if (!continueWithPropertyPopulation) {
return;
}
//获取bean定义的属性
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
// 根据Bean配置的依赖注入方式完成注入,默认是0,即不走以下逻辑,所有的依赖注入都需要在xml文件中有显式的配置
// 如果设置了相关的依赖装配方式,会遍历Bean中的属性,根据类型或名称来完成相应注入,无需额外配置
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
// 深拷贝当前已有的配置
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// 根据名称进行注入
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// // 根据类型进行注入
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
// 结合注入后的配置,覆盖当前配置
pvs = newPvs;
}
// 容器是否注册了InstantiationAwareBeanPostProcessor
/**
* 这里又是一种后置处理,用于在 Spring 填充属性到 bean 对象前,对属性的值进行相应的处理,
* 比如可以修改某些属性的值。这时注入到 bean 中的值就不是配置文件中的内容了,
* 而是经过后置处理器修改后的内容
*/
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
// 是否进行依赖检查
boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
if (hasInstAwareBpps || needsDepCheck) {
// 过滤出所有需要进行依赖检查的属性编辑器
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
// 如果有相关的后置处理器,进行后置处理
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
// 检查是否满足相关依赖关系,对应的depends-on属性,需要确保所有依赖的Bean先完成初始化
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
// 将pvs上所有的属性填充到BeanWrapper对应的Bean实例中
// 其实,上面只是完成了所有注入属性的获取,将获取的属性封装在 PropertyValues 的实例对象 pvs 中,
// 并没有应用到已经实例化的 bean 中。而 #applyPropertyValues 则是完成这一步骤的
applyPropertyValues(beanName, mbd, bw, pvs);
}
九、initializeBean进行初始化
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
// 对特殊的bean进行处理 : 实现了 Aware、BeanClassLoaderAware、BeanFactoryAware 的处理。后面详解
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
// 1.实现了Aware接口进行方法的回调
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 2.调用我们的bean的后置处理器的postProcessorsBeforeInitialization方法
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 3.激活自定义的init的方法。
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
// 4.调用我们bean的后置处理器的PostProcessorsAfterInitialization方法 动态代理就是在这里实现的
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
|