美文网首页springspring
spring源码分析2

spring源码分析2

作者: 念䋛 | 来源:发表于2021-08-20 20:25 被阅读0次

    AbstractApplicationContext#refresh方法的finishBeanFactoryInitialization方法,实例化bean

    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
       // Initialize conversion service for this context.
       if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
             beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
          beanFactory.setConversionService(
                beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
       }
    
       // Register a default embedded value resolver if no bean post-processor
       // (such as a PropertyPlaceholderConfigurer bean) registered any before:
       // at this point, primarily for resolution in annotation attribute values.
       if (!beanFactory.hasEmbeddedValueResolver()) {
          beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
       }
    
       // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
       String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
       for (String weaverAwareName : weaverAwareNames) {
          getBean(weaverAwareName);
       }
    
       // Stop using the temporary ClassLoader for type matching.
       beanFactory.setTempClassLoader(null);
    
       // Allow for caching all bean definition metadata, not expecting further changes.
    //冻结bean,就是将beanFactory的configurationFrozen属性设置为true,不允许修改beanDefinition
       beanFactory.freezeConfiguration();
    
       // Instantiate all remaining (non-lazy-init) singletons.
       beanFactory.preInstantiateSingletons();
    }
    
    
    
    @Override
    public void preInstantiateSingletons() throws BeansException {
       if (logger.isTraceEnabled()) {
          logger.trace("Pre-instantiating singletons in " + this);
       }
    
       // 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.
       List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
    
       // Trigger initialization of all non-lazy singleton beans...
    //获取所有BeanDefinition的名称
       for (String beanName : beanNames) {
    //通过@bean @import @configuration 等存入的beanDefintionMap的value是不同的,但都是BeanDefinition的子类,这里通过名字循环,并用下面的代码都转为RootBeanDefinition①
          RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
    //判断不是抽象类 是单例 不是懒加载
          if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
    //判断是否是FactoryBean的实现类
             if (isFactoryBean(beanName)) {
    //如果是,获取实现FacrotyBean类本身,( FacrotyBean类实现类获取bean是getObject方法的返回值), FACTORY_BEAN_PREFIX 为& 
                Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                if (bean instanceof FactoryBean) {
                   FactoryBean<?> factory = (FactoryBean<?>) bean;
                   boolean isEagerInit;
                   if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                      isEagerInit = AccessController.doPrivileged(
                            (PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
                            getAccessControlContext());
                   }
                   else {
                      isEagerInit = (factory instanceof SmartFactoryBean &&
                            ((SmartFactoryBean<?>) factory).isEagerInit());
                   }
                   if (isEagerInit) {
    // getBean方法中会判断beanName类是否实现了FactoryBean,实现了则调用getObject方法
    //通过AbstractBeanFactory#doGetBean的
    //bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    //代码调用的getObject()方法
                      getBean(beanName);
                   }
                }
             }
             else {
                getBean(beanName);
             }
          }
       }
    
       // Trigger post-initialization callback for all applicable beans...
       for (String beanName : beanNames) {
          Object singletonInstance = getSingleton(beanName);
          if (singletonInstance instanceof SmartInitializingSingleton) {
             StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize")
                   .tag("beanName", beanName);
             SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
             if (System.getSecurityManager() != null) {
                AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                   smartSingleton.afterSingletonsInstantiated();
                   return null;
                }, getAccessControlContext());
             }
             else {
                smartSingleton.afterSingletonsInstantiated();
             }
             smartInitialize.end();
          }
       }
    }
    
    

    ① BeanDefinitionMap的value为不同的类型的beanDefinition
    [图片上传失败...(image-b4b43a-1629462086486)]
    AbstractFacrotyBean#doGetBean方法

    protected <T> T doGetBean(
          String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
          throws BeansException {
    //如果是别名则返回beanDefinitionMap中key的名称,并且去掉FactoryBean用到的&
    //何为别名,@Bean(name) @Bean(name={"tank","tankAlias"}) tank为beanDefinitionMap中的名称, tankAlias为别名,通过tankAlias得到的是tank
       String beanName = transformedBeanName(name);
       Object bean;
    
       // Eagerly check singleton cache for manually registered singletons.
    //从一级缓存中获取,如果是第一次调用,缓存中不会存在, getSingleton方法利用三级缓存解决循环依赖问题,后续会分析
       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 + "'");
             }
          }
    //如果类实现FacrotyBean则在这里调用getObject()方法,返回Bean
          bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
       }
    
       else {
          // Fail if we're already creating this bean instance:
          // We're assumably within a circular reference.
    //如果是多例bean会抛出异常
          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) {
    // 将beanName放到alreadyCreated成员变量中,代表马上就要创建
             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);
    //检查当前创建的bean定义是不是抽象的bean定义
             checkMergedBeanDefinition(mbd, beanName, args);
    
             // Guarantee initialization of beans that the current bean depends on.
    //在上一篇文章中分析解析类的时候将@DependsOn注解将要依赖的Bean名称,放到beanDefinition的dependsOn成员变量中,这里获取出来
    // ClassPathBeanDefinitionScanner# doScan的//AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition//) candidate);方法注入的, processCommonDefinitionAnnotations方法还注入了很多注解//Lazy
    //Primary Role Description等
             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当前类之前,先getBean dependsOn中的类,这里的dep是dependsOn
                      getBean(dep);
                   }
                   catch (NoSuchBeanDefinitionException ex) {
                      throw new BeanCreationException(mbd.getResourceDescription(), beanName,  "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                   }
                }
             }
    
             // Create bean instance.
    //如果bean是单例
             if (mbd.isSingleton()) {
    // getSingleton的主要作用就是赋值bean正在创建状态,并传一个回调函数,lambda表达式
    // createBean此时创建bean
                sharedInstance = getSingleton(beanName, () -> {
                   try {
    //createBean方法,创建Bean的主要方法
                      return createBean(beanName, mbd, args);
                   }
       ……………………省略的代码
       return (T) bean;
    }
    
    

    AbstractAutowireCapableBeanFactory#createBean方法

    @Override
    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);
          mbdToUse.setBeanClass(resolvedClass);
       }
    
       // Prepare method overrides.
       try {
          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.
    //调用第一个Bean的后置处理器InstantiationAwareBeanPostProcessor,项目中不经常使用这个后置处理器,可以返回任意的bean,比如beanName是car,返回值可以返回Tank
          Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
    //如果bean不为null,直接返回了,创建Bean结束了,这是唯一一个可以直接返回Bean的后置处理器
          if (bean != null) {
             return bean;
          }
       }
       catch (Throwable ex) {
          throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
                "BeanPostProcessor before instantiation of bean failed", ex);
       }
    
       try {
    //如果resolveBeforeInstantiation(beanName, mbdToUse)返回null,那真正创建Bean的方法来了
          Object beanInstance = doCreateBean(beanName, mbdToUse, args);
          if (logger.isTraceEnabled()) {
             logger.trace("Finished creating instance of bean '" + beanName + "'");
          }
          return beanInstance;
       }
       catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
          // A previously detected exception with proper bean creation context already,
          // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
          throw ex;
       }
       catch (Throwable ex) {
          throw new BeanCreationException(
                mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
       }
    }
    
    

    AbstractAutowireCapableBeanFacroty#doCreateBean真正创建bean方法

    protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
          throws BeanCreationException {
    
       // Instantiate the bean.
    //bean的包装类
       BeanWrapper instanceWrapper = null;
       if (mbd.isSingleton()) {
          instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
       }
       if (instanceWrapper == null) {
    //创建Bean的关键方法,通过构造函数创建,如果构造函数有入参的话,从容器中取出,并赋值,
    非构造函数入参的成员变量,即使@Autowire标注,也不会赋值,后续代码会赋值
    //这里也就看出了,三级缓存不能解决构造函数的循环依赖
          instanceWrapper = createBeanInstance(beanName, mbd, args);
       }
    //获取bean
       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 {
    //进行后置处理 @AutoWired @Value@Resource的注解的预解析,此时预解析存放在
    // 方法会遍历InstantiationAwareBeanPostProcessor的实现类的postProcessMergedBeanDefinition方法
    //AutowiredAnnotationBeanPostProcessor预解析, @Autowired和@value标注的成员变量
    //CommonAnnotationBeanPostProcessor预解析@Resource标注的成员变量
    //预解析就是将标注@AutoWired @Value@Resource的类放到成员变量injectionMetadataCache
    中,再下面populateBean方法中遍历后置处理器执行postProcessProperties方法,会从injectionMetadataCache取出并赋值
    //这里只是预解析,并没有赋值
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
             }
             catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                      "Post-processing of merged bean definition failed", ex);
             }
             mbd.postProcessed = true;
          }
       }
    
       // Eagerly cache singletons to be able to resolve circular references
       // even when triggered by lifecycle interfaces like BeanFactoryAware.
       boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
             isSingletonCurrentlyInCreation(beanName));
       if (earlySingletonExposure) {
          if (logger.isTraceEnabled()) {
             logger.trace("Eagerly caching bean '" + beanName +
                   "' to allow for resolving potential circular references");
          }
          addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
       }
    
       // Initialize the bean instance.
       Object exposedObject = bean;
       try {
    //bean后置处理器,为@Autowired,@Resource,@Value赋值和xml通过type/name赋值属性,下篇文章分析
          populateBean(beanName, mbd, instanceWrapper);
    //bean的后置处理器和绝大多数的aware的执行 下篇文章分析
          exposedObject = initializeBean(beanName, exposedObject, mbd);
       }
       catch (Throwable ex) {
          if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
             throw (BeanCreationException) ex;
          }
          else {
             throw new BeanCreationException(
                   mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
          }
       }
    
       if (earlySingletonExposure) {
          Object earlySingletonReference = getSingleton(beanName, false);
          if (earlySingletonReference != null) {
             if (exposedObject == bean) {
                exposedObject = earlySingletonReference;
             }
             else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                String[] dependentBeans = getDependentBeans(beanName);
                Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                for (String dependentBean : dependentBeans) {
                   if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                      actualDependentBeans.add(dependentBean);
                   }
                }
                if (!actualDependentBeans.isEmpty()) {
                   throw new BeanCurrentlyInCreationException(beanName,
                         "Bean with name '" + beanName + "' has been injected into other beans [" +
                         StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
                         "] in its raw version as part of a circular reference, but has eventually been " +
                         "wrapped. This means that said other beans do not use the final version of the " +
                         "bean. This is often the result of over-eager type matching - consider using " +
                         "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
                }
             }
          }
       }
    
       // Register bean as disposable.
       try {
          registerDisposableBeanIfNecessary(beanName, bean, mbd);
       }
       catch (BeanDefinitionValidationException ex) {
          throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
       }
    
       return exposedObject;
    }
    
    

    createBeanInstance方法

    protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
       // Make sure bean class is actually resolved at this point.
    //根据beanDefinitionMap中key的名称获取beanClass 如果@Bean beanClass为null
       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?
    //这个方法bean的后置处理器SmartInstantiationAwareBeanPostProcessor
    //这里是子类AutowiredAnnotationBeanPostProcessor
    //作用是确定使用哪个构造函数创建bean,类中没有显示的构造函数,为无参构造函数,
    //如果只有一个有参构造函数,默认就是这个有参构造函数
    //如果有多个有参构造函数,获取标注@Autowired 的有参构造函数
       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) {
    //有参构造函数创建类,并初始化了构造函数的入参,此时构造函数的入参被赋值,但是非入参的//成员变量,即使有@Autowire注释也不会赋值
    //argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, //paramNames,   getUserDeclaredConstructor(candidate), autowiring);将构造函数的入参赋值,所谓的赋值是从IOC容器中获取的bean,不是new的
    
          return autowireConstructor(beanName, mbd, ctors, null);
       }
    //无参构造函数创建类
       // No special handling: simply use no-arg constructor.
       return instantiateBean(beanName, mbd);
    }
    
    

    determineCandidateConstructors实例化类可以使用的构造器

    @Override
    @Nullable
    public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName)
          throws BeanCreationException {
    //@LookUp注解,主要作用解释一下,就是A类是单例 @AutowireB 类,但是B类是多例的,但是A在创建的时候,B就已经初始化到A类,每次使用A类时(C类D类@AutoWire A类),B类是固定的,(当然不同的类@Autowire B类是不同的) @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);
       }
    
       // Quick check on the concurrent map first, with minimal locking.
    //缓存是为了下次直接可以获取可以使用的构造器,能用到下段代码,我分析是在多线程下并且是多例的情况下,两个线程同时创建bean 
       Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
    //为null
       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;
                   }
    //获取标注了@Autowire
                   MergedAnnotation<?> ann = findAutowiredAnnotation(candidate);
                   if (ann == null) {
    //如果没有找到   @Autowire标注的构造器,判断是否是CGlib代理,如果是代理则获取原始类               
    Class<?> userClass = ClassUtils.getUserClass(beanClass);
                      if (userClass != beanClass) {
                         try {
    //获取原始类的所有构造函数
                            Constructor<?> superCtor =                              userClass.getDeclaredConstructor(candidate.getParameterTypes());
    //获取原始类继续查找@Autowire标注的构造器
                            ann = findAutowiredAnnotation(superCtor);
                         }
                         catch (NoSuchMethodException ex) {
                            // Simply proceed, no equivalent superclass constructor found...
                         }
                      }
                   }
    //判断@Autowire 是否为require
                   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]);
                }
    //如果就一个有参构造函数,就算没有被@Autowire标注,依然被返回,这就是我们在项目中经常将所有的成员变量放到构造函数中,也没有标注@Autowire,依然可以注入的原因
                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);
    }
    
    

    AbstractAutowireCapableBeanFacroty#doCreateBean的populateBean和exposedObject两个主要的方法下篇文章继续分析

    相关文章

      网友评论

        本文标题:spring源码分析2

        本文链接:https://www.haomeiwen.com/subject/xdfxiltx.html