Spring源码分析之getBean
一.前言
spring作为JAVAEE最核心的框架,是每一个java开发者所必须掌握的,非常重要,本篇从一个简单例子入手,由浅入深的分析spring创建bean的全过程,目标在于彻底搞懂spring原理,方便以后整合其他框架
二.测试代码
 /**
 * * * @author <a href="mailto:2256222053@qq.com">zc</a>
 * @Date 2022/4/3 0003 14:45
 */
@Lazy
public class CreateBean {  
    private String name;  
 private int age;  
 public CreateBean() {
    }  
    public CreateBean(int age) {
        this.age = age;
 }  
    public CreateBean(String name) {
        this.name = name;
 }  
    public CreateBean(String name, int age) {
        this.name = name;
 this.age = age;
 }  
    public void setName(String name) {
        this.name = name;
 }  
    public void setAge(int age) {
        this.age = age;
 }  
    @Override
 public String toString() {
        return "CreateBean{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
 }
}
- 一个交给spring管理的bean,为了好debug,加了一个懒加载属性
@Test
void doCreateBean(){
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(CreateBean.class);
 Object bean = context.getBean("createBean", "chuan", 24);
 System.out.println(bean);
}
- 一个启动类,getBean是入口,开始创建bean
三. 开始获取bean:getBean()
@Override
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
   assertBeanFactoryActive();
 return getBeanFactory().getBean(name, requiredType);
}
1. 判断容器的活动状态:assertBeanFactoryActive()
容器在启动的时候会设置这个状态值,具体在:AbstractApplicationContext#prepareRefresh()
2.获取beanFactory:getBeanFactory()
从beanFactory中获取bean,默认这个beanFactory是DefaultListableBeanFactory,因为AnnotationConfigApplicationContext继承了GenericApplicationContext,通过他的构造器可以发现
public GenericApplicationContext() {
   this.beanFactory = new DefaultListableBeanFactory();
}
3.getBean(name, requiredType)
通过bean的名称获取bean,第二个参数是bean的类型,如果传了后面会做类型转换,否则就是Object
@Override
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
   return doGetBean(name, requiredType, null, false);
}
getBean:这个类有很多getBean方法,这是使用重载的表现,但是最终都会调用doGetBean,这个方法有四个参数,分别是bean的名称name,bean的类型,创建bean时构造参数的值
四.真正获取Bean的方法:doGetBean()
protected <T> T doGetBean(
      String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
      throws BeansException {  
   String beanName = transformedBeanName(name);
 Object beanInstance;  
 // Eagerly check singleton cache for manually registered singletons.
 Object sharedInstance = getSingleton(beanName);
 if (sharedInstance != null && args == null) {
      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 + "'");
 }
      }
      beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);
 }  
   else {
      // Fail if we're already creating this bean instance:
 // We're assumably within a circular reference. if (isPrototypeCurrentlyInCreation(beanName)) {
         throw new BeanCurrentlyInCreationException(beanName);
 }  
      // Check if bean definition exists in this factory.
 BeanFactory parentBeanFactory = getParentBeanFactory();
 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
         // Not found -> check parent.
 String nameToLookup = originalBeanName(name);
 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);
 }
      }  
      if (!typeCheckOnly) {
         markBeanAsCreated(beanName);
 }  
      StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate")
            .tag("beanName", name);
 try {
         if (requiredType != null) {
            beanCreation.tag("beanType", requiredType::toString);
 }
         RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
 checkMergedBeanDefinition(mbd, beanName, args);  
 // Guarantee initialization of beans that the current bean depends on.
 String[] dependsOn = mbd.getDependsOn();
 if (dependsOn != null) {
            for (String dep : dependsOn) {
               if (isDependent(beanName, dep)) {
                  throw new BeanCreationException(mbd.getResourceDescription(), beanName,
 "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
 }
               registerDependentBean(dep, beanName);
 try {
                  getBean(dep);
 }
               catch (NoSuchBeanDefinitionException ex) {
                  throw new BeanCreationException(mbd.getResourceDescription(), beanName,
 "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
 }
            }
         }  
         // Create bean instance.
 if (mbd.isSingleton()) {
            sharedInstance = getSingleton(beanName, () -> {
               try {
                  return createBean(beanName, mbd, args);
 }
               catch (BeansException ex) {
 throw ex;
 }
            });
 beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
 }  
         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);
 }
            beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
 }  
         else {
            String scopeName = mbd.getScope();
 if (!StringUtils.hasLength(scopeName)) {
               throw new IllegalStateException("No scope name defined for bean '" + beanName + "'");
 }
            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);
 }
               });
 beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
 }
            catch (IllegalStateException ex) {
               throw new ScopeNotActiveException(beanName, scopeName, ex);
 }
         }
      }
      catch (BeansException ex) {
         beanCreation.tag("exception", ex.getClass().toString());
 beanCreation.tag("message", String.valueOf(ex.getMessage()));
 cleanupAfterBeanCreationFailure(beanName);
 throw ex;
 }
      finally {
         beanCreation.end();
 }
   }  
   return adaptBeanInstance(name, beanInstance, requiredType);
}
这个方法很复杂,但是可以简要分为以下几个步骤
1. 获取bean名称
transformedBeanName()
因为可能会有前缀&,获取FactoryBean的情况,所以需要在这解析
2.尝试从缓存中获取bean
getSingleton()
3.判断这个bean是否在创建中
isPrototypeCurrentlyInCreation(beanName)
这一步目的是为了防止循环依赖
4.标记为正在创建中
markBeanAsCreated(beanName):将这个bean
5.合并Definition
getMergedLocalBeanDefinition(beanName)
通过parentName的值来判断是否有父definition,合并的目的在于保证definition的正确性,spring在每次要用definition的时候都会进行一次合并,因为有很多扩展点可以修改definition
6.检查合并后的Definition
checkMergedBeanDefinition(mbd, beanName, args);
7.获取依赖的Bean
mbd.getDependsOn();
如果不为空则会先创建依赖的bean
8.获取真正需要的Bean
getSingleton(beanName,()->{return createBean(beanName, mbd, args);})
获取一个注册好的bean,如果没有,会使用参数FactoryBean注册一个,非常重要,真正创建bean的入口,下面会详细会讲创建过程
getObjectForBeanInstance(sharedInstance, name, beanName, mbd);,如果name有前缀&,那么会返回FactoryBean的实例,如果注册的是一个FactoryBean,这里会调用getObject来返回真正的bean对象
adaptBeanInstance(name, beanInstance, requiredType);最后一步类型转换
五.获取Bean的过程: getSingleton()
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) {
        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 + "'");
}
        beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
           this.suppressedExceptions = new LinkedHashSet<>();
}
        try {
           singletonObject = singletonFactory.getObject();
newSingleton = true;
}
        catch (IllegalStateException ex) {
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;
}
           afterSingletonCreation(beanName);
}
        if (newSingleton) {
           addSingleton(beanName, singletonObject);
}
     }
     return singletonObject;
}
}
1.尝试从一级缓存中获取Bean
Object singletonObject = this.singletonObjects.get(beanName);
我们这里肯定是没有的,如果有则会直接返回
2.将这个Bean标记为创建中
beforeSingletonCreation(beanName);
里面主要操作就是将这个beanName添加进singletonsCurrentlyInCreation数组中,这个数组里面存的都是正在创建的Bean名称
3.创建Bean
singletonObject = singletonFactory.getObject();
singletonFactory是上面传过来的参数,所以这会去调用上面传过来的的createBean方法,这里使用了@FunctionalInterface函数接口,非常精髓,下面会详细分析createBean的过程
4.将这个Bean标记为已创建
afterSingletonCreation(beanName);
对应上面第二步,删除singletonsCurrentlyInCreation的这个beanName,标记他已经创建完成
5.注册Bean
addSingleton(beanName, singletonObject)
注册bean,把上面第三步创建出来的singletonObject添加进一级缓存singletonObjects和单例缓存registeredSingletons中,删除三级缓存singletonFactories和二级缓存earlySingletonObjects中key为beanName的值
六.开始创建Bean: createBean(beanName, mbd, args)
 protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
    if (this.logger.isTraceEnabled()) {
        this.logger.trace("Creating instance of bean '" + beanName + "'");
 }  
    RootBeanDefinition mbdToUse = mbd;
 Class<?> resolvedClass = this.resolveBeanClass(mbd, beanName, new Class[0]);
 if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
        mbdToUse = new RootBeanDefinition(mbd);
 mbdToUse.setBeanClass(resolvedClass);
 }  
    try {
        mbdToUse.prepareMethodOverrides();
 } catch (BeanDefinitionValidationException var9) {
        throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", var9);
 }  
    Object beanInstance;
 try {
        beanInstance = this.resolveBeforeInstantiation(beanName, mbdToUse);
 if (beanInstance != null) {
            return beanInstance;
 }
    } catch (Throwable var10) {
        throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", var10);
 }  
    try {
        beanInstance = this.doCreateBean(beanName, mbdToUse, args);
 if (this.logger.isTraceEnabled()) {
            this.logger.trace("Finished creating instance of bean '" + beanName + "'");
 }  
        return beanInstance;
 } catch (ImplicitlyAppearedSingletonException | BeanCreationException var7) {
        throw var7;
 } catch (Throwable var8) {
        throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", var8);
 }
}
1.加载类
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
2.标记override的属性
mbdToUse.prepareMethodOverrides();
其实就是lookup-method和replace-method两个属性,如果没有重载会记录下来,后面就不会根据参数判断是哪一个具体的方法,减少了系统开销
3,实例化之前后置处理器
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
调用所有实现了InstantiationAwareBeanPostProcessor接口的类的postProcessBeforeInstantiation方法,如果返回不为null,会接着调用所有实现了BeanPostProcessor接口的类的postProcessAfterInitialization方法,然后返回,aop就是在此处实现的,我们这里所有实现了InstantiationAwareBeanPostProcessor接口的类都是默认的,返回的都是null,所以不会执行后置处理器的after方法,会返回一个null,下面是参考代码
@Nullable
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
    Object bean = null;
 if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
        if (!mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {
            Class<?> targetType = this.determineTargetType(beanName, mbd);
 if (targetType != null) {
                bean = this.applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
 if (bean != null) {
                    bean = this.applyBeanPostProcessorsAfterInitialization(bean, beanName);
 }
            }
        }  
        mbd.beforeInstantiationResolved = bean != null;
 }  
    return bean;
}
4.判断第三步返回的bean是否为空
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
   return bean;
}
这一步比较重要,因为如果不为空会直接返回,这代表着不会执行spring创建bean的方法,比如后面的属性注入,aware接口回调,初始化前,初始化,初始化后都不会执行
5.创建Bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
真正开始创建bean的方法,spring真正干活的方法都是以do开头的,我认为这是一种很好的方法命名规则
七.真正开始创建Bean: doCreateBean(beanName, mbdToUse, args)
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
    BeanWrapper instanceWrapper = null;
 if (mbd.isSingleton()) {
        instanceWrapper = (BeanWrapper)this.factoryBeanInstanceCache.remove(beanName);
 }  
    if (instanceWrapper == null) {
        instanceWrapper = this.createBeanInstance(beanName, mbd, args);
 }  
    synchronized(mbd.postProcessingLock) {
        if (!mbd.postProcessed) {
            try {
                this.applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
 } catch (Throwable var17) {
 }  
            mbd.postProcessed = true;
 }
    }  
    boolean earlySingletonExposure = mbd.isSingleton() && this.allowCircularReferences && this.isSingletonCurrentlyInCreation(beanName);
 if (earlySingletonExposure) {  
        this.addSingletonFactory(beanName, () -> {
            return this.getEarlyBeanReference(beanName, mbd, bean);
 });
 }  
    Object exposedObject = bean;  
        this.populateBean(beanName, mbd, instanceWrapper);
        exposedObject = this.initializeBean(beanName, exposedObject, mbd);  
    if (earlySingletonExposure) {
        Object earlySingletonReference = this.getSingleton(beanName, false);
 if (earlySingletonReference != null) {
            if (exposedObject == bean) {
                exposedObject = earlySingletonReference;
 } else if (!this.allowRawInjectionDespiteWrapping && this.hasDependentBean(beanName)) {
                String[] dependentBeans = this.getDependentBeans(beanName);
 Set<String> actualDependentBeans = new LinkedHashSet(dependentBeans.length);
 String[] var12 = dependentBeans;
 int var13 = dependentBeans.length;  
 for(int var14 = 0; var14 < var13; ++var14) {
                    String dependentBean = var12[var14];
 if (!this.removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                        actualDependentBeans.add(dependentBean);
 }
                }
            }
        }
    }  
    try {
        this.registerDisposableBeanIfNecessary(beanName, bean, mbd);
 return exposedObject;
 } catch (BeanDefinitionValidationException var16) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", var16);
 }
}
1.创建bean实例
createBeanInstance(beanName, mbd, args)
2.执行Definition的后置处理器
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName)
spring在这一步实现了对元注解的解析
如果这个bean是单例的且正在创建中,则会加入三级缓存中,目的是暴露bean的引用,解决循环依赖:this.addSingletonFactory(beanName, () -> {
return this.getEarlyBeanReference(beanName, mbd, bean);
})
3.属性填充
populateBean(beanName, mbd, instanceWrapper);
4.初始化bean
initializeBean(beanName, exposedObject, mbd);
5.注册Bean的销毁方法
registerDisposableBeanIfNecessary(beanName, bean, mbd)
到这才真正开始进入创建bean的流程,流程中的每一步都非常复杂,建议还是很模糊的同学自重,避免走火入魔想对我人身攻击的。下面就每个方法重要的点一一解析,严格按照方法的执行先后顺序来说明
1.1 创建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<?> instanceSupplier = mbd.getInstanceSupplier();
 if (instanceSupplier != null) {
      return obtainFromSupplier(instanceSupplier, beanName);
 }  
   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?
 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);
}
1. 通过Supplier接口创建Bean实例
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
   return obtainFromSupplier(instanceSupplier, beanName);
}
我们这里没有使用这个方式,这种方式需要在注册的时候提供如下
public class C implements Supplier<C> {
    @Override
 public C get() {
        System.out.println("Supplier");
 return new C();
 }
}
/**
 * 自定义实例化方法{@link java.util.function.Supplier#get}
 * 源码调用{@link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance}
 */@Test
void supplier(){
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
 context.registerBean(C.class,new C());
 context.refresh();
 context.getBean("c");
}
2. 通过静态工厂或实例工厂创建Bean实例
if (mbd.getFactoryMethodName() != null) {
   return instantiateUsingFactoryMethod(beanName, mbd, args);
}
我们这没有使用工厂的方式,这两种使用方式如下:
实例工厂:
public class FactoryBeanService {
    private static Bean bean = new Bean();
 private FactoryBeanService() {}  
    public Bean createInstance() {
        System.out.println("实例工厂方法实例化bean");
 return bean;
 }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">  
 <bean id="serviceLocator"
 class="com.youlai.laboratory.spring.create.FactoryBeanService"
 />  
 <bean id="factoryBeanService"
 factory-bean="serviceLocator"
 factory-method="createInstance"
 />  
</beans>
@Test
void factoryBean(){
    ClassPathXmlApplicationContext xmlApplicationContext = new ClassPathXmlApplicationContext("classpath:spring/create/FactoryBean.xml");
}
静态工厂:
public class FactoryClassService {
    private static Bean bean = new Bean();
 private FactoryClassService() {}
    public static Bean createInstance() {
        System.out.println("静态工厂方法实例化bean");
 return bean;
 }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">  
 <bean id="factoryClassService"
 class="com.youlai.laboratory.spring.create.FactoryClassService"
 factory-method="createInstance"/>  
</beans>
@Test
void factoryMethod(){
    ClassPathXmlApplicationContext xmlApplicationContext = new ClassPathXmlApplicationContext("classpath:spring/create/FactoryClass.xml");
}
3. 推断可用的构造器
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName)
这一步比较重要,下面会详细分析
@Override
@Nullable
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName)
      throws BeanCreationException {
   // Let's check for lookup methods here...
   if (!this.lookupMethodsChecked.contains(beanName)) {
      if (AnnotationUtils.isCandidateClass(beanClass, Lookup.class)) {
         try {
            Class<?> targetClass = beanClass;
            do {
               ReflectionUtils.doWithLocalMethods(targetClass, method -> {
                  Lookup lookup = method.getAnnotation(Lookup.class);
                  if (lookup != null) {
                     Assert.state(this.beanFactory != null, "No BeanFactory available");
                     LookupOverride override = new LookupOverride(method, lookup.value());
                     try {
                        RootBeanDefinition mbd = (RootBeanDefinition)
                              this.beanFactory.getMergedBeanDefinition(beanName);
                        mbd.getMethodOverrides().addOverride(override);
                     }
                     catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(beanName,
                              "Cannot apply @Lookup to beans without corresponding bean definition");
                     }
                  }
               });
               targetClass = targetClass.getSuperclass();
            }
            while (targetClass != null && targetClass != Object.class);
         }
         catch (IllegalStateException ex) {
            throw new BeanCreationException(beanName, "Lookup method resolution failed", ex);
         }
      }
      this.lookupMethodsChecked.add(beanName);
   }
   // Quick check on the concurrent map first, with minimal locking.
   Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
   if (candidateConstructors == null) {
      // Fully synchronized resolution now...
      synchronized (this.candidateConstructorsCache) {
         candidateConstructors = this.candidateConstructorsCache.get(beanClass);
         if (candidateConstructors == null) {
            Constructor<?>[] rawCandidates;
            try {
               rawCandidates = beanClass.getDeclaredConstructors();
            }
            catch (Throwable ex) {
               throw new BeanCreationException(beanName,
                     "Resolution of declared constructors on bean Class [" + beanClass.getName() +
                     "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
            }
            List<Constructor<?>> candidates = new ArrayList<>(rawCandidates.length);
            Constructor<?> requiredConstructor = null;
            Constructor<?> defaultConstructor = null;
            Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
            int nonSyntheticConstructors = 0;
            for (Constructor<?> candidate : rawCandidates) {
               if (!candidate.isSynthetic()) {
                  nonSyntheticConstructors++;
               }
               else if (primaryConstructor != null) {
                  continue;
               }
               MergedAnnotation<?> ann = findAutowiredAnnotation(candidate);
               if (ann == null) {
                  Class<?> userClass = ClassUtils.getUserClass(beanClass);
                  if (userClass != beanClass) {
                     try {
                        Constructor<?> superCtor =
                              userClass.getDeclaredConstructor(candidate.getParameterTypes());
                        ann = findAutowiredAnnotation(superCtor);
                     }
                     catch (NoSuchMethodException ex) {
                        // Simply proceed, no equivalent superclass constructor found...
                     }
                  }
               }
               if (ann != null) {
                  if (requiredConstructor != null) {
                     throw new BeanCreationException(beanName,
                           "Invalid autowire-marked constructor: " + candidate +
                           ". Found constructor with 'required' Autowired annotation already: " +
                           requiredConstructor);
                  }
                  boolean required = determineRequiredStatus(ann);
                  if (required) {
                     if (!candidates.isEmpty()) {
                        throw new BeanCreationException(beanName,
                              "Invalid autowire-marked constructors: " + candidates +
                              ". Found constructor with 'required' Autowired annotation: " +
                              candidate);
                     }
                     requiredConstructor = candidate;
                  }
                  candidates.add(candidate);
               }
               else if (candidate.getParameterCount() == 0) {
                  defaultConstructor = candidate;
               }
            }
            if (!candidates.isEmpty()) {
               // Add default constructor to list of optional constructors, as fallback.
               if (requiredConstructor == null) {
                  if (defaultConstructor != null) {
                     candidates.add(defaultConstructor);
                  }
                  else if (candidates.size() == 1 && logger.isInfoEnabled()) {
                     logger.info("Inconsistent constructor declaration on bean with name '" + beanName +
                           "': single autowire-marked constructor flagged as optional - " +
                           "this constructor is effectively required since there is no " +
                           "default constructor to fall back to: " + candidates.get(0));
                  }
               }
               candidateConstructors = candidates.toArray(new Constructor<?>[0]);
            }
            else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
               candidateConstructors = new Constructor<?>[] {rawCandidates[0]};
            }
            else if (nonSyntheticConstructors == 2 && primaryConstructor != null &&
                  defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) {
               candidateConstructors = new Constructor<?>[] {primaryConstructor, defaultConstructor};
            }
            else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {
               candidateConstructors = new Constructor<?>[] {primaryConstructor};
            }
            else {
               candidateConstructors = new Constructor<?>[0];
            }
            this.candidateConstructorsCache.put(beanClass, candidateConstructors);
         }
      }
   }
   return (candidateConstructors.length > 0 ? candidateConstructors : null);
}
1.处理@Lookup注解的方法
// Let's check for lookup methods here...
if (!this.lookupMethodsChecked.contains(beanName)) {
   if (AnnotationUtils.isCandidateClass(beanClass, Lookup.class)) {
      try {
         Class<?> targetClass = beanClass;
         do {
            ReflectionUtils.doWithLocalMethods(targetClass, method -> {
               Lookup lookup = method.getAnnotation(Lookup.class);
               if (lookup != null) {
                  Assert.state(this.beanFactory != null, "No BeanFactory available");
                  LookupOverride override = new LookupOverride(method, lookup.value());
                  try {
                     RootBeanDefinition mbd = (RootBeanDefinition)
                           this.beanFactory.getMergedBeanDefinition(beanName);
                     mbd.getMethodOverrides().addOverride(override);
                  }
                  catch (NoSuchBeanDefinitionException ex) {
                     throw new BeanCreationException(beanName,
                           "Cannot apply @Lookup to beans without corresponding bean definition");
                  }
               }
            });
            targetClass = targetClass.getSuperclass();
         }
         while (targetClass != null && targetClass != Object.class);
      }
      catch (IllegalStateException ex) {
         throw new BeanCreationException(beanName, "Lookup method resolution failed", ex);
      }
   }
   this.lookupMethodsChecked.add(beanName);
}
@Lookup注解主要是为了解决在单例依赖原型时,依赖的原型bean会被修改为单例bean
2. 尝试从缓存中获取可用构造器数组
Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
我们这一步获取为空,如果不为空则会跳过下面的3,4,5步骤,执行第六步返回
3. 获取所有构造器
Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
4. 效验是否有可用的构造器,生成可用的构造器数组
循环第二步得到的构造器数组,先判断他是否有@Autowire注解,如果没有@Autowire注解,则通过类名是否含有$$字符判断这个类是否是CJLAB的子类,如果不是则跳过,是子类则获取他带有@Autowire注解的构造器,如果这个构造器有@Autowire注解,先获取required属性的值,如果为false则把构造器加入可用的构造器数组中,如果为true,则判断可用的构造器数组是否为空,不为空则代表着这个类有多个@Autowire标注的构造器并且参数都为必传,这种情况就抛出异常,为空就把这个构造器标注为最终使用的构造器,并且加入可用的构造器数组中
5. 生成可用构造器集合并添加到缓存中
if (!candidates.isEmpty()) {
   // Add default constructor to list of optional constructors, as fallback.
   if (requiredConstructor == null) {
      if (defaultConstructor != null) {
         candidates.add(defaultConstructor);
      }
      else if (candidates.size() == 1 && logger.isInfoEnabled()) {
         logger.info("Inconsistent constructor declaration on bean with name '" + beanName +
               "': single autowire-marked constructor flagged as optional - " +
               "this constructor is effectively required since there is no " +
               "default constructor to fall back to: " + candidates.get(0));
      }
   }
   candidateConstructors = candidates.toArray(new Constructor<?>[0]);
}
else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
   candidateConstructors = new Constructor<?>[] {rawCandidates[0]};
}
else if (nonSyntheticConstructors == 2 && primaryConstructor != null &&
      defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) {
   candidateConstructors = new Constructor<?>[] {primaryConstructor, defaultConstructor};
}
else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {
   candidateConstructors = new Constructor<?>[] {primaryConstructor};
}
else {
   candidateConstructors = new Constructor<?>[0];
}
//添加进缓存中
this.candidateConstructorsCache.put(beanClass, candidateConstructors);
6. 根据可用构造器集合的数量返回
(candidateConstructors.length > 0 ? candidateConstructors : null);
如果构建器集合数量大于0,则返回这个集合,否则返回null
4. 通过候选构造器集合创建Bean实例
autowireConstructor(beanName, mbd, ctors, null);
这一步里面非常复杂,选择性看
	public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd,
			@Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {
		BeanWrapperImpl bw = new BeanWrapperImpl();
		this.beanFactory.initBeanWrapper(bw);
		Constructor<?> constructorToUse = null;
		ArgumentsHolder argsHolderToUse = null;
		Object[] argsToUse = null;
		if (explicitArgs != null) {
			argsToUse = explicitArgs;
		}
		else {
			Object[] argsToResolve = null;
			synchronized (mbd.constructorArgumentLock) {
				constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
				if (constructorToUse != null && mbd.constructorArgumentsResolved) {
					// Found a cached constructor...
					argsToUse = mbd.resolvedConstructorArguments;
					if (argsToUse == null) {
						argsToResolve = mbd.preparedConstructorArguments;
					}
				}
			}
			if (argsToResolve != null) {
				argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve);
			}
		}
		if (constructorToUse == null || argsToUse == null) {
			// Take specified constructors, if any.
			Constructor<?>[] candidates = chosenCtors;
			if (candidates == null) {
				Class<?> beanClass = mbd.getBeanClass();
				try {
					candidates = (mbd.isNonPublicAccessAllowed() ?
							beanClass.getDeclaredConstructors() : beanClass.getConstructors());
				}
				catch (Throwable ex) {
					throw new BeanCreationException(mbd.getResourceDescription(), beanName,
							"Resolution of declared constructors on bean Class [" + beanClass.getName() +
							"] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
				}
			}
			if (candidates.length == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) {
				Constructor<?> uniqueCandidate = candidates[0];
				if (uniqueCandidate.getParameterCount() == 0) {
					synchronized (mbd.constructorArgumentLock) {
						mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
						mbd.constructorArgumentsResolved = true;
						mbd.resolvedConstructorArguments = EMPTY_ARGS;
					}
					bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
					return bw;
				}
			}
			// Need to resolve the constructor.
			boolean autowiring = (chosenCtors != null ||
					mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
			ConstructorArgumentValues resolvedValues = null;
			int minNrOfArgs;
			if (explicitArgs != null) {
				minNrOfArgs = explicitArgs.length;
			}
			else {
				ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
				resolvedValues = new ConstructorArgumentValues();
				minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
			}
			AutowireUtils.sortConstructors(candidates);
			int minTypeDiffWeight = Integer.MAX_VALUE;
			Set<Constructor<?>> ambiguousConstructors = null;
			Deque<UnsatisfiedDependencyException> causes = null;
			for (Constructor<?> candidate : candidates) {
				int parameterCount = candidate.getParameterCount();
				if (constructorToUse != null && argsToUse != null && argsToUse.length > parameterCount) {
					// Already found greedy constructor that can be satisfied ->
					// do not look any further, there are only less greedy constructors left.
					break;
				}
				if (parameterCount < minNrOfArgs) {
					continue;
				}
				ArgumentsHolder argsHolder;
				Class<?>[] paramTypes = candidate.getParameterTypes();
				if (resolvedValues != null) {
					try {
						String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, parameterCount);
						if (paramNames == null) {
							ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
							if (pnd != null) {
								paramNames = pnd.getParameterNames(candidate);
							}
						}
						argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames,
								getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1);
					}
					catch (UnsatisfiedDependencyException ex) {
						if (logger.isTraceEnabled()) {
							logger.trace("Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex);
						}
						// Swallow and try next constructor.
						if (causes == null) {
							causes = new ArrayDeque<>(1);
						}
						causes.add(ex);
						continue;
					}
				}
				else {
					// Explicit arguments given -> arguments length must match exactly.
					if (parameterCount != explicitArgs.length) {
						continue;
					}
					argsHolder = new ArgumentsHolder(explicitArgs);
				}
				int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
						argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
				// Choose this constructor if it represents the closest match.
				if (typeDiffWeight < minTypeDiffWeight) {
					constructorToUse = candidate;
					argsHolderToUse = argsHolder;
					argsToUse = argsHolder.arguments;
					minTypeDiffWeight = typeDiffWeight;
					ambiguousConstructors = null;
				}
				else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
					if (ambiguousConstructors == null) {
						ambiguousConstructors = new LinkedHashSet<>();
						ambiguousConstructors.add(constructorToUse);
					}
					ambiguousConstructors.add(candidate);
				}
			}
			if (constructorToUse == null) {
				if (causes != null) {
					UnsatisfiedDependencyException ex = causes.removeLast();
					for (Exception cause : causes) {
						this.beanFactory.onSuppressedException(cause);
					}
					throw ex;
				}
				throw new BeanCreationException(mbd.getResourceDescription(), beanName,
						"Could not resolve matching constructor on bean class [" + mbd.getBeanClassName() + "] " +
						"(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)");
			}
			else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) {
				throw new BeanCreationException(mbd.getResourceDescription(), beanName,
						"Ambiguous constructor matches found on bean class [" + mbd.getBeanClassName() + "] " +
						"(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " +
						ambiguousConstructors);
			}
			if (explicitArgs == null && argsHolderToUse != null) {
				argsHolderToUse.storeCache(mbd, constructorToUse);
			}
		}
		Assert.state(argsToUse != null, "Unresolved constructor arguments");
		bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
		return bw;
	}
1. 创建一个BeanWrapperImpl并初始化
BeanWrapperImpl bw = new BeanWrapperImpl();
this.beanFactory.initBeanWrapper(bw);
BeanWrapperImpl是用来承载bean实例的,里面封装了
2.对候选的构造器集合排序
AutowireUtils.sortConstructors(candidates);
排序会把修饰符为publi排在前面,其余的修饰符的排在后面,先根据修饰符,然后根据参数的数量排序,参数数量越多的排在越前面,参数越少的排在越后面
3. 创建参数对象
argsHolder = new ArgumentsHolder(explicitArgs);
new ArgumentsHolder(explicitArgs);创建一个保存参数的对象
4. 开始实例化Bean
instantiate(beanName, mbd, constructorToUse, argsToUse)
这里面实例化的方式分为两种
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
      final Constructor<?> ctor, Object... args) {
   if (!bd.hasMethodOverrides()) {
      if (System.getSecurityManager() != null) {
         // use own privileged to change accessibility (when security is on)
         AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            ReflectionUtils.makeAccessible(ctor);
            return null;
         });
      }
      return BeanUtils.instantiateClass(ctor, args);
   }
   else {
      return instantiateWithMethodInjection(bd, beanName, owner, ctor, args);
   }
}
通过判断是否有覆盖方法来选择实例化方式,这里覆盖的方法指的是标题六的第二步
[六.开始创建Bean: createBean(beanName, mbd, args)]:
1. 通过CJLAB来实例化
public Object instantiate(@Nullable Constructor<?> ctor, Object... args) {
   Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
   Object instance;
   if (ctor == null) {
      instance = BeanUtils.instantiateClass(subclass);
   }
   else {
      try {
         Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
         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;
}
如果包含覆盖方法,就会使用上面这种方式实例化Bean,其中加了两个拦截器,来实现方法替换
2. 通过构造器实例化Bean
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];
            }
         }
         return ctor.newInstance(argsWithDefaultValues);
      }
   }
   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());
   }
}
到这终于完成了实例化,真正执行实例化的是通过newInstance(argsWithDefaultValues),newInstance是JAVA提供的一种创建Bean实例的方式,下面回到创建Bean的第二步,也就是创建bean实例的下一步,执行Definition的后置处理器
2.1 执行Definition的后置处理器
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
   for (MergedBeanDefinitionPostProcessor processor : getBeanPostProcessorCache().mergedDefinition) {
      processor.postProcessMergedBeanDefinition(mbd, beanType, beanName);
   }
}
调用MergedBeanDefinitionPostProcessor接口的postProcessMergedBeanDefinition方法,这里获取MergedBeanDefinitionPostProcessor接口默认有三个
- CommonAnnotationBeanPostProcessor : 解析@PostConstruct,@PreDestroy,@Resource注解
- AutowiredAnnotationBeanPostProcessor: 解析@Autowired ,@Value注解
- ApplicationListenerDetector:
2.1.1 解析@PostConstruct,@PreDestroy
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
   super.postProcessMergedBeanDefinition(beanDefinition, beanType, beanName);
   InjectionMetadata metadata = findResourceMetadata(beanName, beanType, null);
   metadata.checkConfigMembers(beanDefinition);
}
- 调用父类,扫描@PostConstruct,@PreDestroy注解的类
- findResourceMetadata:扫描@Resource注解的类
private LifecycleMetadata findLifecycleMetadata(Class<?> clazz) {
   if (this.lifecycleMetadataCache == null) {
      // Happens after deserialization, during destruction...
      return buildLifecycleMetadata(clazz);
   }
   // Quick check on the concurrent map first, with minimal locking.
   LifecycleMetadata metadata = this.lifecycleMetadataCache.get(clazz);
   if (metadata == null) {
      synchronized (this.lifecycleMetadataCache) {
         metadata = this.lifecycleMetadataCache.get(clazz);
         if (metadata == null) {
            metadata = buildLifecycleMetadata(clazz);
            this.lifecycleMetadataCache.put(clazz, metadata);
         }
         return metadata;
      }
   }
   return metadata;
}
- 先从缓存里面获取,如果为空再获取一遍,双重效验 
- buildLifecycleMetadata:构建元数据 
- 添加进缓存lifecycleMetadataCache中 - buildLifecycleMetadata - private LifecycleMetadata buildLifecycleMetadata(final Class<?> clazz) {
 do {
 final List<LifecycleElement> currInitMethods = new ArrayList<>();
 final List<LifecycleElement> currDestroyMethods = new ArrayList<>(); ReflectionUtils.doWithLocalMethods(targetClass, method -> {
 //
 if (this.initAnnotationType != null && method.isAnnotationPresent(this.initAnnotationType)) {
 LifecycleElement element = new LifecycleElement(method);
 currInitMethods.add(element);
 if (logger.isTraceEnabled()) {
 logger.trace("Found init method on class [" + clazz.getName() + "]: " + method);
 }
 }
 if (this.destroyAnnotationType != null && method.isAnnotationPresent(this.destroyAnnotationType)) {
 currDestroyMethods.add(new LifecycleElement(method));
 if (logger.isTraceEnabled()) {
 logger.trace("Found destroy method on class [" + clazz.getName() + "]: " + method);
 }
 }
 });
 initMethods.addAll(0, currInitMethods);
 destroyMethods.addAll(currDestroyMethods);
 targetClass = targetClass.getSuperclass();
 }
 while (targetClass != null && targetClass != Object.class); return (initMethods.isEmpty() && destroyMethods.isEmpty() ? this.emptyLifecycleMetadata :
 new LifecycleMetadata(clazz, initMethods, destroyMethods));
 }
 
- 查找标注了PostConstruct和PreDestroy注解的方法,通过isAnnotationPresent来判断,分别加入到currInitMethods和currDestroyMethods数组,最后再封装到 
LifecycleMetadata类里面
2.1.2 解析@Resource
private InjectionMetadata findResourceMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
   // Fall back to class name as cache key, for backwards compatibility with custom callers.
   String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
   // Quick check on the concurrent map first, with minimal locking.
   InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
   if (InjectionMetadata.needsRefresh(metadata, clazz)) {
      synchronized (this.injectionMetadataCache) {
         metadata = this.injectionMetadataCache.get(cacheKey);
         if (InjectionMetadata.needsRefresh(metadata, clazz)) {
            if (metadata != null) {
               metadata.clear(pvs);
            }
            metadata = buildResourceMetadata(clazz);
            this.injectionMetadataCache.put(cacheKey, metadata);
         }
      }
   }
   return metadata;
}
这一步和上面一样,先使用双重效验检查缓存,如果有则直接返回,没有则创建
buildResourceMetadata(clazz)
private InjectionMetadata buildResourceMetadata(Class<?> clazz) {
      ReflectionUtils.doWithLocalFields(targetClass, field -> {
          if (field.isAnnotationPresent(Resource.class)) {
            if (Modifier.isStatic(field.getModifiers())) {
               throw new IllegalStateException("@Resource annotation is not supported on static fields");
            }
            if (!this.ignoredResourceTypes.contains(field.getType().getName())) {
               currElements.add(new ResourceElement(field, field, null));
            }
         }
      });
      ReflectionUtils.doWithLocalMethods(targetClass, method -> {
       if (bridgedMethod.isAnnotationPresent(Resource.class)) {
               if (Modifier.isStatic(method.getModifiers())) {
                  throw new IllegalStateException("@Resource annotation is not supported on static methods");
               }
               Class<?>[] paramTypes = method.getParameterTypes();
               if (paramTypes.length != 1) {
                  throw new IllegalStateException("@Resource annotation requires a single-arg method: " + method);
               }
               if (!this.ignoredResourceTypes.contains(paramTypes[0].getName())) {
                  PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                  currElements.add(new ResourceElement(method, bridgedMethod, pd));
               }
      });
      elements.addAll(0, currElements);
      targetClass = targetClass.getSuperclass();
   }
   while (targetClass != null && targetClass != Object.class);
   return InjectionMetadata.forElements(elements, clazz);
}
先扫描字段,再扫描方法,判断是否有static修饰符,如果有则报错,注意这里还检查了参数,只有一个参数的时候才会添加到elements数组中,最后封装到InjectionMetadata对象里
2.1.3解析@Autowired,@Value
AutowiredAnnotationBeanPostProcessor#findAutowiringMetadata
private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
   // Fall back to class name as cache key, for backwards compatibility with custom callers.
   String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
   // Quick check on the concurrent map first, with minimal locking.
   InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
   if (InjectionMetadata.needsRefresh(metadata, clazz)) {
      synchronized (this.injectionMetadataCache) {
         metadata = this.injectionMetadataCache.get(cacheKey);
         if (InjectionMetadata.needsRefresh(metadata, clazz)) {
            if (metadata != null) {
               metadata.clear(pvs);
            }
            metadata = buildAutowiringMetadata(clazz);
            this.injectionMetadataCache.put(cacheKey, metadata);
         }
      }
   }
   return metadata;
}
这里和上面一样,先使用双重效验检查缓存,如果有则直接返回,没有则创建
AutowiredAnnotationBeanPostProcessor#buildAutowiringMetadata
private InjectionMetadata buildAutowiringMetadata(Class<?> clazz) {
   do {
      final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
      ReflectionUtils.doWithLocalFields(targetClass, field -> {
         MergedAnnotation<?> ann = findAutowiredAnnotation(field);
         if (ann != null) {
            if (Modifier.isStatic(field.getModifiers())) {
               if (logger.isInfoEnabled()) {
                  logger.info("Autowired annotation is not supported on static fields: " + field);
               }
               return;
            }
            boolean required = determineRequiredStatus(ann);
            currElements.add(new AutowiredFieldElement(field, required));
         }
      });
      ReflectionUtils.doWithLocalMethods(targetClass, method -> {
         MergedAnnotation<?> ann = findAutowiredAnnotation(bridgedMethod);
         if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
            if (Modifier.isStatic(method.getModifiers())) {
               if (logger.isInfoEnabled()) {
                  logger.info("Autowired annotation is not supported on static methods: " + method);
               }
               return;
            }
            if (method.getParameterCount() == 0) {
               if (logger.isInfoEnabled()) {
                  logger.info("Autowired annotation should only be used on methods with parameters: " +
                        method);
               }
            }
            boolean required = determineRequiredStatus(ann);
            PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
            currElements.add(new AutowiredMethodElement(method, required, pd));
         }
      });
      elements.addAll(0, currElements);
      targetClass = targetClass.getSuperclass();
   }
   while (targetClass != null && targetClass != Object.class);
   return InjectionMetadata.forElements(elements, clazz);
}
通过findAutowiredAnnotation查找带有@Autowired,@Value的属性和方法
@Nullable
private MergedAnnotation<?> findAutowiredAnnotation(AccessibleObject ao) {
   MergedAnnotations annotations = MergedAnnotations.from(ao);
   for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) {
      MergedAnnotation<?> annotation = annotations.get(type);
      if (annotation.isPresent()) {
         return annotation;
      }
   }
   return null;
}
this.autowiredAnnotationTypes在构造方法时添加
public AutowiredAnnotationBeanPostProcessor() {
   this.autowiredAnnotationTypes.add(Autowired.class);
   this.autowiredAnnotationTypes.add(Value.class);
}
到此类的元数据就解析完了,最后还有一个ApplicationListenerDetector
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
   if (ApplicationListener.class.isAssignableFrom(beanType)) {
      this.singletonNames.put(beanName, beanDefinition.isSingleton());
   }
}
这里就是记录一下这个bean是否是单例
3.1 属性填充
下面分析这个方法内部是怎么实现属性填充的
populateBean(beanName, mbd, instanceWrapper);
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
   if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
      for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
         if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
            return;
         }
      }
   }
   PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
   int resolvedAutowireMode = mbd.getResolvedAutowireMode();
   if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
      MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
      // Add property values based on autowire by name if applicable.
      if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
         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);
      }
      pvs = newPvs;
   }
   boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
   boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
   PropertyDescriptor[] filteredPds = null;
   if (hasInstAwareBpps) {
      if (pvs == null) {
         pvs = mbd.getPropertyValues();
      }
      for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
         PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
         if (pvsToUse == null) {
            if (filteredPds == null) {
               filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
            }
            pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
            if (pvsToUse == null) {
               return;
            }
         }
         pvs = pvsToUse;
      }
   }
   if (needsDepCheck) {
      if (filteredPds == null) {
         filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
      }
      checkDependencies(beanName, mbd, filteredPds, pvs);
   }
   if (pvs != null) {
      applyPropertyValues(beanName, mbd, bw, pvs);
   }
}
3.1.1 调用实现了InstantiationAwareBeanPostProcessor接口的postProcessAfterInstantiation方法,如果返回false则中断下面的属性填充,目的是为了让用户可以自定义属性注入
3.1.2 获取注入方式,根据注入方式解析属性到PropertyValues类里
3.1.3 对标注@AutoWired的属性进行依赖注入
3.1.4 依赖检查: checkDependencies(beanName, mbd, filteredPds, pvs)
3.1.5 applyPropertyValues,将解析的值用BeanWrapper进行包装
4.1 初始化bean
initializeBean(beanName, exposedObject, mbd)
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
   if (System.getSecurityManager() != null) {
      AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
         invokeAwareMethods(beanName, bean);
         return null;
      }, getAccessControlContext());
   }
   else {
      invokeAwareMethods(beanName, bean);
   }
   Object wrappedBean = bean;
   if (mbd == null || !mbd.isSynthetic()) {
      wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
   }
   try {
      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()) {
      wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
   }
   return wrappedBean;
}
4.1.1调用各种aware接口:invokeAwareMethods
4.1.2:执行初始化前置操作:applyBeanPostProcessorsBeforeInitialization
4.1.3:初始化:InitializingBean
4.1.4:调用method-init初始化方法
4.1.5:执行初始化后置操作:applyBeanPostProcessorsAfterInitialization
5 .1注册bean的销毁方法
5.1.1 检查是否实现DisposableBean 接口以及指定的销毁方法和注册的 DestructionAwareBeanPostProcessors
protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) {
   return (bean.getClass() != NullBean.class && (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) ||
         (hasDestructionAwareBeanPostProcessors() && DisposableBeanAdapter.hasApplicableProcessors(
               bean, getBeanPostProcessorCache().destructionAware))));
}
5.1.2 将bean的添加到注册表,完成注册
public void registerDisposableBean(String beanName, DisposableBean bean) {
   synchronized (this.disposableBeans) {
      this.disposableBeans.put(beanName, bean);
   }
}
Spring源码分析之getBean的更多相关文章
- Spring源码分析——BeanFactory体系之抽象类、类分析(二)
		上一篇分析了BeanFactory体系的2个类,SimpleAliasRegistry和DefaultSingletonBeanRegistry——Spring源码分析——BeanFactory体系之 ... 
- spring源码分析(二)Aop
		创建日期:2016.08.19 修改日期:2016.08.20-2016.08.21 交流QQ:992591601 参考资料:<spring源码深度解析>.<spring技术内幕&g ... 
- 【Spring源码分析】Bean加载流程概览
		代码入口 之前写文章都会啰啰嗦嗦一大堆再开始,进入[Spring源码分析]这个板块就直接切入正题了. 很多朋友可能想看Spring源码,但是不知道应当如何入手去看,这个可以理解:Java开发者通常从事 ... 
- 【Spring源码分析】非懒加载的单例Bean初始化过程(上篇)
		代码入口 上文[Spring源码分析]Bean加载流程概览,比较详细地分析了Spring上下文加载的代码入口,并且在AbstractApplicationContext的refresh方法中,点出了f ... 
- 【Spring源码分析】非懒加载的单例Bean初始化前后的一些操作
		前言 之前两篇文章[Spring源码分析]非懒加载的单例Bean初始化过程(上篇)和[Spring源码分析]非懒加载的单例Bean初始化过程(下篇)比较详细地分析了非懒加载的单例Bean的初始化过程, ... 
- 【Spring源码分析】原型Bean实例化过程、byName与byType及FactoryBean获取Bean源码实现
		原型Bean加载过程 之前的文章,分析了非懒加载的单例Bean整个加载过程,除了非懒加载的单例Bean之外,Spring中还有一种Bean就是原型(Prototype)的Bean,看一下定义方式: & ... 
- 【spring源码分析】IOC容器初始化(七)
		前言:在[spring源码分析]IOC容器初始化(六)中分析了从单例缓存中加载bean对象,由于篇幅原因其核心函数 FactoryBeanRegistrySupport#getObjectFromFa ... 
- 【spring源码分析】IOC容器初始化(十)
		前言:前文[spring源码分析]IOC容器初始化(九)中分析了AbstractAutowireCapableBeanFactory#createBeanInstance方法中通过工厂方法创建bean ... 
- 【spring源码分析】IOC容器初始化——查漏补缺(一)
		前言:在[spring源码分析]IOC容器初始化(十一)中提到了初始化bean的三个步骤: 激活Aware方法. 后置处理器应用(before/after). 激活自定义的init方法. 这里我们就来 ... 
- Spring 源码分析之 bean 依赖注入原理(注入属性)
		最近在研究Spring bean 生命周期相关知识点以及源码,所以打算写一篇 Spring bean生命周期相关的文章,但是整理过程中发现涉及的点太多而且又很复杂,很难在一篇文章中把Spri ... 
随机推荐
- js-禁止鼠标右键/禁止选中文字
			1 <p>使用contextmenu禁止鼠标右键</p> 2 <script> 3 document.addEventListener('contextmenu', ... 
- eclipse中同步git代码报错checkout conflict with files
			1.Team--->Synchronize Workspace 2.在同步窗口找到冲突文件,把自己本地修改的复制出来 3.在文件上右键选择 Overwrite----->Yes , 4.再 ... 
- spring的作用
			Spring能有效地组织你的中间层对象,无论你是否选择使用了EJB.如果你仅仅使用了Struts或其他的包含了J2EE特有API的framework,你会发现Spring关注了遗留下的问题.Sprin ... 
- eureka注册中心增加登录认证
			https://www.cnblogs.com/gxloong/p/12364523.html 开启Eureka注册中心认证 1.目的描述 Eureka自带了一个Web的管理页面,方便我们查询注册 ... 
- MeanShift 均值漂移算法
			MeanShift, 它常被用在图像识别中的目标跟踪,数据聚类.分类等场景 
- egg框架学习笔记
			1.安装 npm i egg-init -g egg-init egg-example --type=simple cd egg-example yarn install npm run dev // ... 
- verilog 硬件描述语言
			第一章 绪论 verilog--数字电路设计技术--ASIC/SOC芯片设计--协议pcie SATA USB--系统知识(个人计算机,芯片组,网络连接,嵌入式系统,硬件和软件的互操作) 第二章 寄存 ... 
- 正则爬取'豆瓣之乘风破浪的姐姐'的并存入excel文档
			import requests import re import pandas as pd def parse_page(url): headers = { 'User-Agent':'Mozilla ... 
- CSS 常用样式-文本属性
			文本类样式我们已经学习过颜色 color 属性,严格来说行高 line-height 也是文本类属性,由于其可以合写在 font 属性中个,暂时先归类到字体中学习,接下来还有几个常用的文本属性. 水平 ... 
- 关于数据传递 json
			关于这几种语言的json 操作 Lua local cjson2 = require "cjson" local lua_object = { ["name"] ... 
