`

spring4.0源码分析━━━(实例化bean)

 
阅读更多

          前面有一篇说了spring的解析xml,解析xml最终的作用就是生成BeanDefinition。而实例化的时候会先得到BeanDefinition,而这BeanDefinition已经包含了实例化所有的属性,包括class,property等。详细见前面文章。

         解析xml的时候是没有初始化的,而是在第一次getBean的时候才会实例化,当然也可以通过lazy-init这个属性来控制。也就是启动的时候是否加载。一般的情况下是会加载,虽然比较慢。但是比到使用的时候再加载更加的快。因为有些业务需要很快处理完成,而你加载又浪费掉一段时间。所以一般情况下是启动就加载了。无论是否lazy-init,实例化调用的都是AbstractBeanFactory类的getBean(String beanName)方法。spring实例化的时候不仅仅是简单的new一个bean,其实有很多的工作。图片如下:



 

    这里我只是详细的讲解第一步和第二部。后面的几步就放到后面去讲,AOP的实现实际是和BeanPostProcessor有很大的关系。其实AOP的实现就是用BeanPostProcessor来实现的。实例化和设置属性的调用图如下:

    AbstractBeanFactory.getBean --> AbstractBeanFactory.doGetBean -->                AbstractBeanFactory.getMergedLocalBeanDefinition --> DefaultListableBeanFactory.getBeanDefinition --> AbstractAutowireCapableBeanFactory.createBean --> AbstractAutowireCapableBeanFactory.doCreateBean --> AbstractAutowireCapableBeanFactory.createBeanInstance -->AbstractAutowireCapableBeanFactory.populateBean

           其中实例化是调用到SimpleInstantiationStrategy类的

public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) {
		// Don't override the class with CGLIB if no overrides.
		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 new BeanInstantiationException(clazz, "Specified class is an interface");
					}
					try {
						if (System.getSecurityManager() != null) {
							constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor>() {
								public Constructor run() throws Exception {
									return clazz.getDeclaredConstructor((Class[]) null);
								}
							});
						}
						else {
							constructorToUse =	clazz.getDeclaredConstructor((Class[]) null);
						}
						beanDefinition.resolvedConstructorOrFactoryMethod = constructorToUse;
					}
					catch (Exception ex) {
						throw new BeanInstantiationException(clazz, "No default constructor found", ex);
					}
				}
			}
			return BeanUtils.instantiateClass(constructorToUse);
		}
		else {
			// Must generate CGLIB subclass.
			return instantiateWithMethodInjection(beanDefinition, beanName, owner);
		}
	}

 

上面的实例化有通过JVM的反射和CGLIB两种方式实例化bean,默认是JVM的反射。这里就是通过class得到构造函数然后实例化。而属性的实例化则是会调用到AbstractAutowireCapableBeanFactory的applyPropertyValues方法。而最终会是在BeanWrapperImpl类中一下方法

private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
  String propertyName = tokens.canonicalName;
  String actualName = tokens.actualName;

  if (tokens.keys != null) {
   // Apply indexes and map keys: fetch value for all keys but the last one.
   PropertyTokenHolder getterTokens = new PropertyTokenHolder();
   getterTokens.canonicalName = tokens.canonicalName;
   getterTokens.actualName = tokens.actualName;
   getterTokens.keys = new String[tokens.keys.length - 1];
   System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
   Object propValue;
   try {
    propValue = getPropertyValue(getterTokens);
   }
   catch (NotReadablePropertyException ex) {
    throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
      "Cannot access indexed value in property referenced " +
      "in indexed property path '" + propertyName + "'", ex);
   }
   // Set value for last key.
   String key = tokens.keys[tokens.keys.length - 1];
   if (propValue == null) {
    throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
      "Cannot access indexed value in property referenced " +
      "in indexed property path '" + propertyName + "': returned null");
   }
   else if (propValue.getClass().isArray()) {
    PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
    Class requiredType = propValue.getClass().getComponentType();
    int arrayIndex = Integer.parseInt(key);
    Object oldValue = null;
    try {
     if (isExtractOldValueForEditor()) {
      oldValue = Array.get(propValue, arrayIndex);
     }
     Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
       new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), requiredType));
     Array.set(propValue, arrayIndex, convertedValue);
    }
    catch (IndexOutOfBoundsException ex) {
     throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
       "Invalid array index in property path '" + propertyName + "'", ex);
    }
   }
   else if (propValue instanceof List) {
    PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
    Class requiredType = GenericCollectionTypeResolver.getCollectionReturnType(
      pd.getReadMethod(), tokens.keys.length);
    List list = (List) propValue;
    int index = Integer.parseInt(key);
    Object oldValue = null;
    if (isExtractOldValueForEditor() && index < list.size()) {
     oldValue = list.get(index);
    }
    Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
      new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), requiredType));
    if (index < list.size()) {
     list.set(index, convertedValue);
    }
    else if (index >= list.size()) {
     for (int i = list.size(); i < index; i++) {
      try {
       list.add(null);
      }
      catch (NullPointerException ex) {
       throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
         "Cannot set element with index " + index + " in List of size " +
         list.size() + ", accessed using property path '" + propertyName +
         "': List does not support filling up gaps with null elements");
      }
     }
     list.add(convertedValue);
    }
   }
   else if (propValue instanceof Map) {
    PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
    Class mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(
      pd.getReadMethod(), tokens.keys.length);
    Class mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(
      pd.getReadMethod(), tokens.keys.length);
    Map map = (Map) propValue;
    // IMPORTANT: Do not pass full property name in here - property editors
    // must not kick in for map keys but rather only for map values.
    Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType,
      new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), mapKeyType));
    Object oldValue = null;
    if (isExtractOldValueForEditor()) {
     oldValue = map.get(convertedMapKey);
    }
    // Pass full property name and old value in here, since we want full
    // conversion ability for map values.
    Object convertedMapValue = convertIfNecessary(
      propertyName, oldValue, pv.getValue(), mapValueType,
      new TypeDescriptor(new MethodParameter(pd.getReadMethod(), -1, tokens.keys.length + 1)));
    map.put(convertedMapKey, convertedMapValue);
   }
   else {
    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
      "Property referenced in indexed property path '" + propertyName +
      "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue() + "]");
   }
  }

  else {
   PropertyDescriptor pd = pv.resolvedDescriptor;
   if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
    pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
    if (pd == null || pd.getWriteMethod() == null) {
     if (pv.isOptional()) {
      logger.debug("Ignoring optional value for property '" + actualName +
        "' - property not found on bean class [" + getRootClass().getName() + "]");
      return;
     }
     else {
      PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
      throw new NotWritablePropertyException(
        getRootClass(), this.nestedPath + propertyName,
        matches.buildErrorMessage(), matches.getPossibleMatches());
     }
    }
    pv.getOriginalPropertyValue().resolvedDescriptor = pd;
   }

   Object oldValue = null;
   try {
    Object originalValue = pv.getValue();
    Object valueToApply = originalValue;
    if (!Boolean.FALSE.equals(pv.conversionNecessary)) {
     if (pv.isConverted()) {
      valueToApply = pv.getConvertedValue();
     }
     else {
      if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
       final Method readMethod = pd.getReadMethod();
       if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) &&
         !readMethod.isAccessible()) {
        if (System.getSecurityManager()!= null) {
         AccessController.doPrivileged(new PrivilegedAction<Object>() {
          public Object run() {
           readMethod.setAccessible(true);
           return null;
          }
         });
        }
        else {
         readMethod.setAccessible(true);
        }
       }
       try {
        if (System.getSecurityManager() != null) {
         oldValue = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
          public Object run() throws Exception {
           return readMethod.invoke(object);
          }
         }, acc);
        }
        else {
         oldValue = readMethod.invoke(object);
        }
       }
       catch (Exception ex) {
        if (ex instanceof PrivilegedActionException) {
         ex = ((PrivilegedActionException) ex).getException();
        }
        if (logger.isDebugEnabled()) {
         logger.debug("Could not read previous value of property '" +
           this.nestedPath + propertyName + "'", ex);
        }
       }
      }
      valueToApply = convertForProperty(propertyName, oldValue, originalValue, pd);
     }
     pv.getOriginalPropertyValue().conversionNecessary = (valueToApply != originalValue);
    }
    final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor ?
      ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess() :
      pd.getWriteMethod());
    if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers()) && !writeMethod.isAccessible()) {
     if (System.getSecurityManager()!= null) {
      AccessController.doPrivileged(new PrivilegedAction<Object>() {
       public Object run() {
        writeMethod.setAccessible(true);
        return null;
       }
      });
     }
     else {
      writeMethod.setAccessible(true);
     }
    }
    final Object value = valueToApply;
    if (System.getSecurityManager() != null) {
     try {
      AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
       public Object run() throws Exception {
        writeMethod.invoke(object, value);
        return null;
       }
      }, acc);
     }
     catch (PrivilegedActionException ex) {
      throw ex.getException();
     }
    }
    else {
     writeMethod.invoke(this.object, value);
    }
   }
   catch (TypeMismatchException ex) {
    throw ex;
   }
   catch (InvocationTargetException ex) {
    PropertyChangeEvent propertyChangeEvent =
      new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue());
    if (ex.getTargetException() instanceof ClassCastException) {
     throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException());
    }
    else {
     throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
    }
   }
   catch (Exception ex) {
    PropertyChangeEvent pce =
      new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue());
    throw new MethodInvocationException(pce, ex);
   }
  }
 }

 

其中的PropertyTokenHolder是发现如果属性中有配置[],即配置了向一下的

<property name="father.array[0]" value="1" />
    <property name="father.array[1]" value="2" />
    <property name="map[a]" value="2" />

等就会使用到PropertyTokenHolder,并且里面的keys则不为空。如果没有则是使用到PropertyDescriptor,然后得到javabean的writeMethod方法设置属性。在BeanWrapperImpl是有一个缓存的机制缓存了bean的内省结果,这样就更加的快速得到bean的PropertyDescriptor,从而得到writeMethod。其中的值是直接是通过PropertyValue得到,在解析xml的时候已经完整的设置好了。这里还有一个概念,如果发现bean是关联到了另外的bean,则关联的bean是在本身的bean前被实例化并设置好属性,知道发现没有关联其他的bean。

       到这里就算实例化bean和设置属性完成了。这里用到的知识点就是JVM的反射和JavaBean的内省等。而在这里的时候又会发现读取xml的时候为什么不简单的使用map保存属性,而是用PropertyValue来了,这里PropertyValue中的PropertyDescriptor、convertedValue都使用到了。其中的convertedValue在解析时并不是我们使用到的String类型等,像String类型对应的是TypedStringValue,而是到这里才会转换成String类型。并设置PropertyValue的convertedValue的值。

  • 大小: 55.1 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics