spring的bean加载2

本文详细解析了Spring框架中单例Bean的创建过程,包括从缓存获取单例、初始化前的准备、依赖解析、实例化、初始化及后置处理等关键步骤。

5.4获取单例

如果之前从缓存中获取单例,缓存中不存在已经加载的单例bean,就需要从头开始加载,也就是getSingleton方法。

 

public Object getSingleton(StringbeanName,ObjectFactory<?> singletonFactory) {

      Assert.notNull(beanName, "'beanName' must not be null");

      synchronized (this.singletonObjects) {//全局变量需同步

//(1)检查是否已经加载过,没有则进行singleton的bean初始化,利用Objectfactory的getObject方法,前提是(ObjectFactoryBean应该存在,没有销毁)

         ObjectsingletonObject= this.singletonObjects.get(beanName);

         if (singletonObject == null) {

            if (this.singletonsCurrentlyInDestruction){

               throw new BeanCreationNotAllowedException(beanName,

                      "Singleton bean creation not allowed while thesingletons of this factory are in destruction "+

                      "(Do not request a bean from a BeanFactory in adestroy method implementation!)");

            }

            if (logger.isDebugEnabled()) {

                logger.debug("Creating shared instance of singleton bean '" + beanName+ "'");

            }

//(2)相应的工厂ObjectFactory在调用其方法创建前,需要执行before方法,并记录引发的异常

            beforeSingletonCreation(beanName);

            boolean recordSuppressedExceptions= (this.suppressedExceptions== null);

            if (recordSuppressedExceptions){

                this.suppressedExceptions= newLinkedHashSet<Exception>();

            }

            try {

//(3)然后利用singletonFactory的getObject方法进行bean对象初始化

                singletonObject = singletonFactory.getObject();

            }

            catch (BeanCreationException ex) {

                if (recordSuppressedExceptions){

                   for (Exception suppressedException: this.suppressedExceptions){

                      ex.addRelatedCause(suppressedException);

                   }

                }

                throw ex;

            }

            finally {

                if (recordSuppressedExceptions){

                   this.suppressedExceptions= null;

                }

//(4)创建bean之后需要执行after的方法

                afterSingletonCreation(beanName);

            }

//(5)创建成功的bean需要加入到singleton的缓存中,以备下次使用

            addSingleton(beanName, singletonObject);

         }

         return (singletonObject != NULL_OBJECT? singletonObject: null);

      }

   }

其过程也就是检查缓存中是否有加载过;若没有加载,则记录beanName的正在加载状态;加载单例前记录加载状态(也就是beforeSingletonCreation方法);通过调用参数闯入objectFactory的个体object方法实例化bean;加载单例后的处理方法的调用(移除缓存中对于该bean的正在加载状态的记录)。将结果记录值缓存并删除加载bean过程中所记录的各种辅助状态。摘自《spring源码深度解析》

(a1)这里主要讲解创建之前beforeSingletonCreation(beanName);

protected voidbeforeSingletonCreation(StringbeanName){

      if (!this.inCreationCheckExclusions.containsKey(beanName) &&

            this.singletonsCurrentlyInCreation.put(beanName, Boolean.TRUE) != null) {

         throw newBeanCurrentlyInCreationException(beanName);

      }

   }

这里是主要检查beanName不包含在inCreationCheckExclusions中,但是singletonsCurrentlyInCreation中将该bean加入了其中,这两者应该是互斥的,也就是beanName应该在inCreationCheckExclusions中,同时singletonCurrentlyInCreation中也加入了该bean,然后才会执行下一步的createBean操作。这是创建之前的检查准备工作。因为singletonCurrentlyInCreation是map<key,value>的形式,如果有相同的key,那么对应的value将会被后者所代替。

(a2)解析bean的依赖

singletonObject = singletonFactory.getObject();

singletonFactory获取对象getObject,

#DefaultListavleBeanFactory:getObject()

public Object getObject()throwsBeansException {

         return doResolveDependency(this.descriptor, this.descriptor.getDependencyType(), this.beanName, null, null);

      }

进行相应的依赖解析,这里判断了array/collection/map/其他的情形

protected Object doResolveDependency(DependencyDescriptordescriptor,Class<?> type,String beanName,

         Set<String>autowiredBeanNames,TypeConverter typeConverter)throwsBeansException {

 

      Objectvalue= getAutowireCandidateResolver().getSuggestedValue(descriptor);

      if (value != null) {

         if (value instanceof String) {

            StringstrVal= resolveEmbeddedValue((String) value);

            BeanDefinitionbd = (beanName != null &&containsBean(beanName)? getMergedBeanDefinition(beanName) : null);

            value =evaluateBeanDefinitionString(strVal, bd);

         }

         TypeConverterconverter= (typeConverter!= null? typeConverter: getTypeConverter());

         return (descriptor.getField() != null ?

                converter.convertIfNecessary(value, type, descriptor.getField()) :

                converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));

      }

 

      if (type.isArray()) {

         Class<?>componentType= type.getComponentType();

         Map<String,Object> matchingBeans= findAutowireCandidates(beanName, componentType,descriptor);

         if (matchingBeans.isEmpty()) {

            if (descriptor.isRequired()) {

                raiseNoSuchBeanDefinitionException(componentType, "array of "+ componentType.getName(),descriptor);

            }

            return null;

         }

         if (autowiredBeanNames!= null){

            autowiredBeanNames.addAll(matchingBeans.keySet());

         }

         TypeConverterconverter= (typeConverter!= null? typeConverter: getTypeConverter());

         return converter.convertIfNecessary(matchingBeans.values(), type);

      }

      else if (Collection.class.isAssignableFrom(type) && type.isInterface()) {

         Class<?>elementType= descriptor.getCollectionType();

         if (elementType == null) {

            if (descriptor.isRequired()) {

                throw new FatalBeanException("No element type declared for collection [" + type.getName()+ "]");

            }

            return null;

         }

         Map<String,Object> matchingBeans= findAutowireCandidates(beanName, elementType,descriptor);

         if (matchingBeans.isEmpty()) {

            if (descriptor.isRequired()) {

                raiseNoSuchBeanDefinitionException(elementType, "collection of "+ elementType.getName(),descriptor);

            }

            return null;

         }

         if (autowiredBeanNames!= null){

            autowiredBeanNames.addAll(matchingBeans.keySet());

         }

         TypeConverterconverter= (typeConverter!= null? typeConverter: getTypeConverter());

         return converter.convertIfNecessary(matchingBeans.values(), type);

      }

      else if (Map.class.isAssignableFrom(type) && type.isInterface()) {

         Class<?>keyType= descriptor.getMapKeyType();

         if (keyType == null || !String.class.isAssignableFrom(keyType)) {

            if (descriptor.isRequired()) {

                throw new FatalBeanException("Key type ["+ keyType+ "] of map [" + type.getName()+

                      "] must be assignable to [java.lang.String]");

            }

            return null;

         }

         Class<?>valueType= descriptor.getMapValueType();

         if (valueType == null) {

            if (descriptor.isRequired()) {

                throw new FatalBeanException("No value type declared for map [" + type.getName()+ "]");

            }

            return null;

         }

         Map<String,Object> matchingBeans= findAutowireCandidates(beanName, valueType,descriptor);

         if (matchingBeans.isEmpty()) {

            if (descriptor.isRequired()) {

                raiseNoSuchBeanDefinitionException(valueType, "map with value type "+ valueType.getName(),descriptor);

            }

            return null;

         }

         if (autowiredBeanNames!= null){

            autowiredBeanNames.addAll(matchingBeans.keySet());

         }

         return matchingBeans;

      }

      else {

         Map<String,Object> matchingBeans= findAutowireCandidates(beanName, type,descriptor);

         if (matchingBeans.isEmpty()) {

            if (descriptor.isRequired()) {

                raiseNoSuchBeanDefinitionException(type, "", descriptor);

            }

            return null;

         }

         if (matchingBeans.size() > 1) {

            StringprimaryBeanName= determinePrimaryCandidate(matchingBeans, descriptor);

            if (primaryBeanName == null) {

                throw newNoUniqueBeanDefinitionException(type, matchingBeans.keySet());

            }

            if (autowiredBeanNames!= null){

                autowiredBeanNames.add(primaryBeanName);

            }

            return matchingBeans.get(primaryBeanName);

         }

         // We have exactly one match.

         Map.Entry<String,Object> entry= matchingBeans.entrySet().iterator().next();

         if (autowiredBeanNames!= null){

            autowiredBeanNames.add(entry.getKey());

         }

         return entry.getValue();

      }

   }

(a3)这里说的是after之后的afterSingletonCreation中的事情:

   protected void afterSingletonCreation(String beanName) {

      if (!this.inCreationCheckExclusions.containsKey(beanName) &&

            !this.singletonsCurrentlyInCreation.remove(beanName)) {

         throw new IllegalStateException("Singleton '"+ beanName+ "' isn't currently in creation");

      }

   }

创建之后要执行的清理工作的判断,实例化后inCreationCheckExclusions包含该beanName,同时singletonCurrentlyInCreation中应该成功移除并且返回该beanName的对象。

其实对于bean的创建,到这里我们还是比较晕晕乎乎的,到底什么时候创建的bean?

5.5准备创建bean,真正的单例的bean创建在这里createbean()

// Create bean instance.

            if (mbd.isSingleton()) {

                sharedInstance = getSingleton(beanName, newObjectFactory<Object>() {

                   public Object getObject() throws BeansException {

                      try {

                         return createBean(beanName, mbd, args);

                      }

                      catch (BeansException ex) {

                         // Explicitly remove instance from singleton cache: Itmight have been put there

                         // eagerly by the creation process, to allow for circularreference resolution.

                         // Also remove any beans that received a temporaryreference to the bean.

                         destroySingleton(beanName);

                         throw ex;

                      }

                   }

                });

                bean =getObjectForBeanInstance(sharedInstance, name,beanName,mbd);

            }

这里使用匿名内部类,ObjectFactory来创建的bean,

#AbstractAutowireCapableBeanFactory:

@Override

   protected ObjectcreateBean(finalString beanName,finalRootBeanDefinition mbd,finalObject[] args)

         throws BeanCreationException {

 

      if (logger.isDebugEnabled()) {

         logger.debug("Creating instance of bean '" + beanName+ "'");

      }

      // 确保beanclass被解析

      resolveBeanClass(mbd, beanName);

//预处理方法重写,是针对于lookup-method和replace-method标签的

      try {

         mbd.prepareMethodOverrides();

      }

      catch(BeanDefinitionValidationException ex) {

         throw newBeanDefinitionStoreException(mbd.getResourceDescription(),

                beanName, "Validation of method overrides failed", ex);

      }

 

      try {

         // BeanPostProcessors返回一个目标bean实例的代理.

         Objectbean= resolveBeforeInstantiation(beanName, mbd);

         if (bean != null) {

            return bean;

         }

      }

      catch (Throwable ex) {

         throw new BeanCreationException(mbd.getResourceDescription(),beanName,

                "BeanPostProcessor before instantiation of beanfailed", ex);

      }

上面的步骤是:(b1)根据设置的class属性或者根据classname来解析class;

            (b2)对override属性进行标记和验证(对于lookup-method,replace-method的);

            (b3)应用初始化前的后处理器,解析指定bean是否存在初始化前的短路操作(bean实例化的代理);

            (b4)创建常规bean;

   下面就研究创建常规bean(b4)//如果返回的目标bean的代理为null,则使用下面的方法

      ObjectbeanInstance= doCreateBean(beanName,mbd,args);

      if (logger.isDebugEnabled()) {

         logger.debug("Finished creating instance of bean '" + beanName+ "'");

      }

      return beanInstance;

   }

这里重点研究doCreatBean:,该方法是实例化有各种有区别的bean的

*/

   protected ObjectdoCreateBean(finalString beanName,finalRootBeanDefinition mbd,finalObject[] args){

      // Instantiate the bean.beanWrapperbean的包装器(接口)BEANWrapperIMpl实现了该接口,是spring框架的javabean的核心接口

      BeanWrapperinstanceWrapper= null;

      if (mbd.isSingleton()) {

         instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);

      }

      if (instanceWrapper == null) {

//使用相应的策略创建相应的bean

         instanceWrapper =createBeanInstance(beanName,mbd,args);

      }

      final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance(): null);

     Class<?>beanType= (instanceWrapper!= null? instanceWrapper.getWrappedClass(): null);

 

      // 允许后处理器修改合并的beandefintion.

      synchronized (mbd.postProcessingLock){

         if (!mbd.postProcessed) {

            applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);

            mbd.postProcessed = true;

         }

      }

 

// Eagerly cache singletons 可以解析 circular references

// 是否需要提早曝光:单例&允许循环依赖&当前bean正在创建中,检查循环依赖

      boolean earlySingletonExposure= (mbd.isSingleton()&& this.allowCircularReferences&&

            isSingletonCurrentlyInCreation(beanName));

      if (earlySingletonExposure){

         if (logger.isDebugEnabled()) {

            logger.debug("Eagerly caching bean '" + beanName+

                   "' to allow for resolving potential circularreferences");

         }

      //为避免后期循环依赖,可以再bean初始化完成前将创建实例的objectFactory加入工厂

addSingletonFactory(beanName, newObjectFactory<Object>() {

            public Object getObject() throws BeansException {

                return getEarlyBeanReference(beanName, mbd, bean);

            }

         });

      }

//初始化实例

      ObjectexposedObject= bean;

      try {//对bean进行填充,将各个属性值注入,其中,可能存在依赖于其他bean的属性,则会递归初始依赖bean

         populateBean(beanName, mbd, instanceWrapper);

         if (exposedObject != null) {//调用初始化方法

            exposedObject =initializeBean(beanName,exposedObject,mbd);

         }

      }

      catch (Throwable ex) {

         if (ex instanceofBeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {

            throw (BeanCreationException)ex;

         }

         else {

            throw new BeanCreationException(mbd.getResourceDescription(),beanName,"Initialization of bean failed", ex);

         }

      }

 

      if (earlySingletonExposure){

         ObjectearlySingletonReference = getSingleton(beanName, false);

         if (earlySingletonReference!= null){

            if (exposedObject == bean) {

                exposedObject = earlySingletonReference;

            }

            else if (!this.allowRawInjectionDespiteWrapping&& hasDependentBean(beanName)) {

                String[]dependentBeans= getDependentBeans(beanName);

                Set<String>actualDependentBeans = newLinkedHashSet<String>(dependentBeans.length);

                for (String dependentBean : dependentBeans) {

                   if(!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {

                      actualDependentBeans.add(dependentBean);

                   }

                }

                if (!actualDependentBeans.isEmpty()){

                   throw newBeanCurrentlyInCreationException(beanName,

                         "Bean with name '"+ beanName+ "' has been injected into other beans[" +

                         StringUtils.collectionToCommaDelimitedString(actualDependentBeans)+

                         "] in its raw version as part of a circularreference, but has eventually been "+

                         "wrapped. This means that said other beans do notuse the final version of the " +

                         "bean. This is often the result of over-eager typematching - consider using " +

                         "'getBeanNamesOfType' with the 'allowEagerInit' flagturned 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;

   }

思路:

(1)  如果是单例则需要首先清楚缓存

(2)  实例化bean,将beandefinition转换为BeanWrapper.

createBeanInstance转换是一个复杂的过程,但是可以试着概括一下:

(a1)如果存在工厂方法则使用工厂方法进行初始化

(a2)一个自动装载的构造器方法初始化(根据参数不同选择不同构造器)

(a3)普通构造器方法

(3)  锁定beandefinition,MergedBeanDefinitionPostProcessor的应用:应用后处理器beandefinition合并merge

(4)  earlySingletonExposure:单例&允许循环引用&bean正在创建的状态,将objectFactory加入到单例工厂缓存中用于处理循环引用的情况.提前暴露出来objectFactory

(5)  方法populatedBean填充bean属性,初始化bean

(6)  早期单例暴露的情况:如果是单例&允许循环引用&bean正在创建,尝试直接获得bean引用,如果非单例模式如prototype的bean,spring则会抛出异常。

(7)  注册DisPosableBean。主要是对于destroy-method的方法而言的

(8)  返回

 

 5.7.1创建bean实例:

上面第二步中主要是调用createBeanInstance方法,创建beanWrapper对象,其实它是一个接口,BeanWrapperImpl才是对象

   protected BeanWrapper createBeanInstance(StringbeanName,RootBeanDefinition mbd,Object[] args){

      // 解析class

      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 notallowed: " + beanClass.getName());

      }

//工厂方法进行实例化bean

      if (mbd.getFactoryMethodName()!= null)  {

         returninstantiateUsingFactoryMethod(beanName, mbd,args);

      }

//对已经有的bean进行重新创建

      // 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);

         }

      }

//需要根据参数类型等选择对应的构造器类型

      // Need to determine the constructor...

     Constructor<?>[]ctors= determineConstructorsFromBeanPostProcessors(beanClass, beanName);

      if (ctors != null ||

            mbd.getResolvedAutowireMode()== RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||

            mbd.hasConstructorArgumentValues()|| !ObjectUtils.isEmpty(args))  {

         return autowireConstructor(beanName, mbd, ctors, args);

      }

 

      // No special handling: simply use no-arg constructor.

      return instantiateBean(beanName, mbd);

   }

该方法的细节如下:

(d1)如果在rootBeanDefinition中存在factoryMethodName属性,或者说配置文件中配置了factory-method,那么spring会尝试使用instantiateUsingFactoryMethod方法根据rootbeandefinition中配置生产bean实例。

(d2)解析构造函数并进行构造函数的实例化。因为bean中可能有多个构造函数,根据参数类型等可以判断具体使用的那个构造函数实例化。因为判断可能耗性能,因此这里采用缓存机制。如果已经解析过则不需要重复解析而是直接从rootbeandefinition中的属性resolvedConstructorOrFactoryMethod缓存中获得,否则在此解析,并将结果加入rootbeandefinition中的属性resolvedConstructorOrFactoryMethod中。

 

1. autowireConstructor

对于实力的创建spring中分成了两种情况,一种是通用的实例化,另一种是带有参数的自动加载的实例化。

带参数的比较复杂,如下:

public BeanWrapper autowireConstructor(

         final String beanName, final RootBeanDefinition mbd, Constructor<?>[]chosenCtors,finalObject[] explicitArgs){

 

      BeanWrapperImplbw = new BeanWrapperImpl();

      this.beanFactory.initBeanWrapper(bw);

 

      Constructor<?>constructorToUse= null;

      ArgumentsHolderargsHolderToUse= 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) {

         // Need to resolve the constructor.

         boolean autowiring = (chosenCtors != null ||

                mbd.getResolvedAutowireMode()== RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);

         ConstructorArgumentValuesresolvedValues= null;

 

         int minNrOfArgs;

         if (explicitArgs != null) {

            minNrOfArgs = explicitArgs.length;

         }

         else {

            ConstructorArgumentValuescargs= mbd.getConstructorArgumentValues();

            resolvedValues = newConstructorArgumentValues();

            minNrOfArgs =resolveConstructorArguments(beanName, mbd,bw, cargs, resolvedValues);

         }

 

         // 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);

            }

         }

         AutowireUtils.sortConstructors(candidates);

         int minTypeDiffWeight= Integer.MAX_VALUE;

         Set<Constructor<?>>ambiguousConstructors = null;

         List<Exception>causes= null;

 

         for (int i = 0; i < candidates.length; i++) {

            Constructor<?>candidate= candidates[i];

            Class<?>[]paramTypes= candidate.getParameterTypes();

 

            if (constructorToUse != null && argsToUse.length > paramTypes.length) {

                // Already found greedy constructor that can be satisfied->

                // do not look any further, there are only less greedyconstructors left.

                break;

            }

            if (paramTypes.length < minNrOfArgs) {

                continue;

            }

 

            ArgumentsHolderargsHolder;

            if (resolvedValues != null) {

                try {

                   String[]paramNames= null;

                   if (constructorPropertiesAnnotationAvailable) {

                      paramNames =ConstructorPropertiesChecker.evaluate(candidate, paramTypes.length);

                   }

                   if (paramNames == null) {

                      ParameterNameDiscovererpnd= this.beanFactory.getParameterNameDiscoverer();

                      if (pnd != null) {

                         paramNames = pnd.getParameterNames(candidate);

                      }

                   }

                   argsHolder = createArgumentArray(

                         beanName, mbd, resolvedValues, bw, paramTypes, paramNames, candidate, autowiring);

                }

                catch(UnsatisfiedDependencyException ex) {

                   if (this.beanFactory.logger.isTraceEnabled()) {

                      this.beanFactory.logger.trace(

                            "Ignoring constructor [" + candidate+ "] of bean '" + beanName+ "': "+ ex);

                   }

                   if (i == candidates.length - 1 && constructorToUse == null) {

                      if (causes != null) {

                         for (Exception cause : causes) {

                            this.beanFactory.onSuppressedException(cause);

                         }

                      }

                      throw ex;

                   }

                   else {

                      // Swallow and try next constructor.

                      if (causes == null) {

                         causes = newLinkedList<Exception>();

                      }

                      causes.add(ex);

                      continue;

                   }

                }

            }

            else {

                // Explicit arguments given -> arguments length mustmatch exactly.

                if (paramTypes.length != explicitArgs.length) {

                   continue;

                }

                argsHolder = new ArgumentsHolder(explicitArgs);

            }

 

            int typeDiffWeight = (mbd.isLenientConstructorResolution()?

                   argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));

            // Choose this constructor if it represents the closestmatch.

            if (typeDiffWeight < minTypeDiffWeight){

                constructorToUse = candidate;

                argsHolderToUse = argsHolder;

                argsToUse = argsHolder.arguments;

                minTypeDiffWeight= typeDiffWeight;

                ambiguousConstructors= null;

            }

            else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight){

                if (ambiguousConstructors== null){

                   ambiguousConstructors= newLinkedHashSet<Constructor<?>>();

                   ambiguousConstructors.add(constructorToUse);

                }

                ambiguousConstructors.add(candidate);

            }

         }

 

         if (constructorToUse == null) {

            throw new BeanCreationException(mbd.getResourceDescription(),beanName,

                   "Could not resolve matching constructor " +

                   "(hint: specify index/type/name arguments for simpleparameters to avoid type ambiguities)");

         }

         else if (ambiguousConstructors!= null&& !mbd.isLenientConstructorResolution()){

            throw new BeanCreationException(mbd.getResourceDescription(),beanName,

                   "Ambiguous constructor matches found in bean '" + beanName+ "' "+

                   "(hint: specify index/type/name arguments for simpleparameters to avoid type ambiguities): "+

                   ambiguousConstructors);

         }

 

         if (explicitArgs == null) {

            argsHolderToUse.storeCache(mbd, constructorToUse);

         }

      }

 

      try {

         ObjectbeanInstance;

 

         if (System.getSecurityManager()!= null){

            final Constructor<?> ctorToUse = constructorToUse;

            final Object[] argumentsToUse = argsToUse;

            beanInstance =AccessController.doPrivileged(new PrivilegedAction<Object>() {

                public Object run() {

                   return beanFactory.getInstantiationStrategy().instantiate(

                         mbd, beanName, beanFactory, ctorToUse, argumentsToUse);

                }

            },beanFactory.getAccessControlContext());

         }

         else {

            beanInstance = this.beanFactory.getInstantiationStrategy().instantiate(

                   mbd, beanName, this.beanFactory, constructorToUse, argsToUse);

         }

 

         bw.setWrappedInstance(beanInstance);

         return bw;

      }

      catch (Throwable ex) {

         throw new BeanCreationException(mbd.getResourceDescription(),beanName,"Instantiation of bean failed", ex);

      }

   }

2不带参数的初始化,则比较简单

protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {

      try {

         ObjectbeanInstance;

         final BeanFactory parent = this;

         if (System.getSecurityManager()!= null){

            beanInstance =AccessController.doPrivileged(new PrivilegedAction<Object>() {

                public Object run() {

                   returngetInstantiationStrategy().instantiate(mbd, beanName, parent);

                }

            },getAccessControlContext());

         }

         else {

            beanInstance =getInstantiationStrategy().instantiate(mbd, beanName, parent);

         }

         BeanWrapperbw = new BeanWrapperImpl(beanInstance);

         initBeanWrapper(bw);

         return bw;

      }

      catch (Throwable ex) {

         throw new BeanCreationException(mbd.getResourceDescription(),beanName,"Instantiation of bean failed", ex);

      }

   }

 

这里使用了实例化的策略,如果

 

   public Object instantiate(RootBeanDefinitionbeanDefinition,String beanName,BeanFactory owner){

      //如果有需要覆盖或者动态替换的方法当然需要使用cglib进行动态代理,如果没有需要动态改变的方法,为了方便可以直接反射就好。.

      if (beanDefinition.getMethodOverrides().isEmpty()){

         Constructor<?>constructorToUse;

         synchronized (beanDefinition.constructorArgumentLock){

            constructorToUse =(Constructor<?>) beanDefinition.resolvedConstructorOrFactoryMethod;

            if (constructorToUse == null) {

                final Class<?> clazz = beanDefinition.getBeanClass();

                if (clazz.isInterface()) {

                   throw newBeanInstantiationException(clazz, "Specified class is an interface");

                }

                try {

                   if (System.getSecurityManager()!= null){

                      constructorToUse =AccessController.doPrivileged(newPrivilegedExceptionAction<Constructor>() {

                         public Constructor<?>run() throwsException {

                            return clazz.getDeclaredConstructor((Class[])null);

                         }

                      });

                   }

                   else {

                      constructorToUse = clazz.getDeclaredConstructor((Class[]) null);

                   }

                   beanDefinition.resolvedConstructorOrFactoryMethod = constructorToUse;

                }

                catch (Exception ex) {

                   throw newBeanInstantiationException(clazz, "No default constructor found", ex);

                }

            }

         }

         return BeanUtils.instantiateClass(constructorToUse);

      }

      else {

         // Must generate CGLIB subclass.

         returninstantiateWithMethodInjection(beanDefinition, beanName,owner);

      }

   }

 

 

CglibSubclassInstantiationStrategy:

public Object instantiate(Constructor<?> ctor, Object[] args) {

         Enhancerenhancer= newEnhancer();

         enhancer.setSuperclass(this.beanDefinition.getBeanClass());

         enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);

         enhancer.setCallbackFilter(new CallbackFilterImpl());

         enhancer.setCallbacks(new Callback[] {

                NoOp.INSTANCE,

                newLookupOverrideMethodInterceptor(),

                newReplaceOverrideMethodInterceptor()

         });

 

         return (ctor != null ? enhancer.create(ctor.getParameterTypes(), args) : enhancer.create());

      }

上面的两端代码时:如果beanDefinition.getMethodOverrides()为空也就是用户没有使用replace或者lookup的配置方法,那么直接使用反射方式;如果是使用了就必须使用动态代理方式将包含两个特性所对应的逻辑的拦截增强器设置进去,这样在调用方法的时候会被相应的拦截器增强,返回值为包含拦截器的代理实例。

其中代码比较多,想法是先理出个答题思路,以后继续写


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值