一个bean中多个构造函数,spring是如何选择构造函数实例化的

1,006 阅读2分钟
1. 主要流程,智摘录了主要代码
protected BeanWrapper createBeanInstance(String beanName, 
          RootBeanDefinition mbd, @Nullable Object[] args) {
    /**
     * 获取符合条件的构造器,优先级如下
     * 1,标记为@Autowired的属性required是true
     * 2,默认构造函数 + 标记为@Autowired
     * 3,有参构造函数
     * 4,其他的情况
     * 5,再就是匹配不上
     */
    Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
				mbd.hasConstructorArgumentValues() ||              
                                !ObjectUtils.isEmpty(args)) {
    /**
     * 从候选的构造函数中返回合适的构造函数
     * 1,根据构造函数的参数个数,由大到小排序,如果参数个数相同则按系统排序
     * 2,如果在处理构造函数中某个参数抛出异常时,捕获异常后继续寻找下一个合适构造函数
     * 3,在遍历正常的构造函数时,根据权重计算方式获取最后的构造函数
     */
      return autowireConstructor(beanName, mbd, ctors, args);
    }
   //使用默认的构造函数,默认情况为null
    ctors = mbd.getPreferredConstructors();
    if (ctors != null) {
        return autowireConstructor(beanName, mbd, ctors, null);
    }
    //使用无参的构造函数
    return instantiateBean(beanName, mbd);
}
2. determineCandidateConstructors(),获取候选的构造函数
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName)throws BeanCreationException {
   candidateConstructors = this.candidateConstructorsCache.get(beanClass);
   if (candidateConstructors == null) {
        Constructor<?>[] rawCandidates;
        try {
            //获取构造函数
            rawCandidates = beanClass.getDeclaredConstructors();
        }catch (Throwable ex) {
        }
        List<Constructor<?>> candidates = new ArrayList<>(rawCandidates.length);
        Constructor<?> requiredConstructor = null;
        Constructor<?> defaultConstructor = null;
        //获取Kotlin类的构造函数,一般来说是返回null
        Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
        int nonSyntheticConstructors = 0;
        for (Constructor<?> candidate : rawCandidates) {
             if (!candidate.isSynthetic()) {
                   nonSyntheticConstructors++;
                 }else if (primaryConstructor != null) {
                   continue;
                 }
                 //判断构造函数是否标记了@Autowired
                 AnnotationAttributes ann = findAutowiredAnnotation(candidate);
                 if (ann == null) {
                     Class<?> userClass = ClassUtils.getUserClass(beanClass);
                     if (userClass != beanClass) {
                     	try {
                             Constructor<?> superCtor = 			
                     userClass.getDeclaredConstructor(candidate.getParameterTypes());
                               //获取父类的构造函数是否标记@Autowired
                               ann = findAutowiredAnnotation(superCtor);
                              }
                              catch (NoSuchMethodException ex) {}
                          }
                      }
                      if (ann != null) {
                      	 //如果存在@Autowired标记的构造函数
                          if (requiredConstructor != null) {
                              throw new BeanCreationException(beanName,
                                      "Invalid autowire-marked constructor: " + candidate 
                                      + ". Found constructor with 'required' Autowired 	
                                      annotation already: " + requiredConstructor);
                          }
                          boolean required = determineRequiredStatus(ann);
                          //如果@Autowired的属性required是true
                          if (required) {
                              /**
                               *如果之前处理的构造函数中存在@Autowired的属性required是true
                               *则抛异常
                               */
                              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;
                      }
                  }
                  //遍历所有的构造存在@Autowired标记的构造函数
                  if (!candidates.isEmpty()) {
                  /**
                   *不存在@Autowired的属性required是true的构造函数且默认构造函数存在,
                   *就将默认函数添加到匹配函数集合中返回
                   */
                      if (requiredConstructor == null) {
                          if (defaultConstructor != null) {
                              candidates.add(defaultConstructor);
                          }
                          else if (candidates.size() == 1 && logger.isInfoEnabled()) {
                              //打印日志,代码省略
                          }
                      }
                      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);
}