首页

关于spring-beans包AutowireUtils自动注入工具类实现自动对象注入获取相关操作源码说明

标签:spring-beans,AutowireUtils,自动注入工具类,springframework     发布时间:2018-09-05   

一、前言

关于spring-beans包中org.springframework.beans.factory.support.AutowireUtils自动注入工具类,对bean容器按照入参多少排序sortConstructors、获取autowaire自动注入的beans工厂对象等相关方法。

二、源码说明

package org.springframework.beans.factory.support;@b@@b@import java.beans.PropertyDescriptor;@b@import java.io.Serializable;@b@import java.lang.reflect.Constructor;@b@import java.lang.reflect.InvocationHandler;@b@import java.lang.reflect.InvocationTargetException;@b@import java.lang.reflect.Method;@b@import java.lang.reflect.Modifier;@b@import java.lang.reflect.ParameterizedType;@b@import java.lang.reflect.Proxy;@b@import java.lang.reflect.Type;@b@import java.lang.reflect.TypeVariable;@b@import java.util.Arrays;@b@import java.util.Comparator;@b@import java.util.Set;@b@import org.springframework.beans.BeanMetadataElement;@b@import org.springframework.beans.factory.ObjectFactory;@b@import org.springframework.beans.factory.config.TypedStringValue;@b@import org.springframework.util.Assert;@b@import org.springframework.util.ClassUtils;@b@@b@abstract class AutowireUtils@b@{@b@  public static void sortConstructors(Constructor<?>[] constructors)@b@  {@b@    Arrays.sort(constructors, new Comparator()@b@    {@b@      public int compare(Constructor<?> c1, Constructor<?> c2) {@b@        boolean p1 = Modifier.isPublic(c1.getModifiers());@b@        boolean p2 = Modifier.isPublic(c2.getModifiers());@b@        if (p1 != p2)@b@          return ((p1) ? -1 : 1);@b@@b@        int c1pl = c1.getParameterTypes().length;@b@        int c2pl = c2.getParameterTypes().length;@b@        return ((c1pl > c2pl) ? -1 : (c1pl < c2pl) ? 1 : 0);@b@      }@b@    });@b@  }@b@@b@  public static void sortFactoryMethods(Method[] factoryMethods)@b@  {@b@    Arrays.sort(factoryMethods, new Comparator()@b@    {@b@      public int compare(Method fm1, Method fm2) {@b@        boolean p1 = Modifier.isPublic(fm1.getModifiers());@b@        boolean p2 = Modifier.isPublic(fm2.getModifiers());@b@        if (p1 != p2)@b@          return ((p1) ? -1 : 1);@b@@b@        int c1pl = fm1.getParameterTypes().length;@b@        int c2pl = fm2.getParameterTypes().length;@b@        return ((c1pl > c2pl) ? -1 : (c1pl < c2pl) ? 1 : 0);@b@      }@b@    });@b@  }@b@@b@  public static boolean isExcludedFromDependencyCheck(PropertyDescriptor pd)@b@  {@b@    Method wm = pd.getWriteMethod();@b@    if (wm == null)@b@      return false;@b@@b@    if (!(wm.getDeclaringClass().getName().contains("$$")))@b@    {@b@      return false;@b@    }@b@@b@    Class superclass = wm.getDeclaringClass().getSuperclass();@b@    return (!(ClassUtils.hasMethod(superclass, wm.getName(), wm.getParameterTypes())));@b@  }@b@@b@  public static boolean isSetterDefinedInInterface(PropertyDescriptor pd, Set<Class<?>> interfaces)@b@  {@b@    Class targetClass;@b@    Method setter = pd.getWriteMethod();@b@    if (setter != null) {@b@      targetClass = setter.getDeclaringClass();@b@      for (Class ifc : interfaces)@b@        if ((ifc.isAssignableFrom(targetClass)) && @b@          (ClassUtils.hasMethod(ifc, setter@b@          .getName(), setter.getParameterTypes())))@b@          return true;@b@@b@    }@b@@b@    return false;@b@  }@b@@b@  public static Object resolveAutowiringValue(Object autowiringValue, Class<?> requiredType)@b@  {@b@    if ((autowiringValue instanceof ObjectFactory) && (!(requiredType.isInstance(autowiringValue)))) {@b@      ObjectFactory factory = (ObjectFactory)autowiringValue;@b@      if ((autowiringValue instanceof Serializable) && (requiredType.isInterface())) {@b@        autowiringValue = Proxy.newProxyInstance(requiredType.getClassLoader(), new Class[] { requiredType }, new ObjectFactoryDelegatingInvocationHandler(factory));@b@      }@b@      else@b@      {@b@        return factory.getObject();@b@      }@b@    }@b@    return autowiringValue;@b@  }@b@@b@  public static Class<?> resolveReturnTypeForFactoryMethod(Method method, Object[] args, ClassLoader classLoader)@b@  {@b@    int i;@b@    int i;@b@    Assert.notNull(method, "Method must not be null");@b@    Assert.notNull(args, "Argument array must not be null");@b@    Assert.notNull(classLoader, "ClassLoader must not be null");@b@@b@    TypeVariable[] declaredTypeVariables = method.getTypeParameters();@b@    Type genericReturnType = method.getGenericReturnType();@b@    Type[] methodParameterTypes = method.getGenericParameterTypes();@b@    Assert.isTrue(args.length == methodParameterTypes.length, "Argument array does not match parameter count");@b@@b@    boolean locallyDeclaredTypeVariableMatchesReturnType = false;@b@    TypeVariable[] arrayOfTypeVariable1 = declaredTypeVariables; int j = arrayOfTypeVariable1.length; for (int k = 0; k < j; ++k) { TypeVariable currentTypeVariable = arrayOfTypeVariable1[k];@b@      if (currentTypeVariable.equals(genericReturnType)) {@b@        locallyDeclaredTypeVariableMatchesReturnType = true;@b@        break;@b@      }@b@    }@b@@b@    if (locallyDeclaredTypeVariableMatchesReturnType)@b@      for (i = 0; i < methodParameterTypes.length; ++i) {@b@        Type[] arrayOfType1;@b@        int i1;@b@        Type methodParameterType = methodParameterTypes[i];@b@        Object arg = args[i];@b@        if (methodParameterType.equals(genericReturnType)) {@b@          if (arg instanceof TypedStringValue) {@b@            TypedStringValue typedValue = (TypedStringValue)arg;@b@            if (typedValue.hasTargetType())@b@              return typedValue.getTargetType();@b@            try@b@            {@b@              return typedValue.resolveTargetType(classLoader);@b@            }@b@            catch (ClassNotFoundException ex)@b@            {@b@              throw new IllegalStateException("Failed to resolve value type [" + typedValue@b@                .getTargetTypeName() + "] for factory method argument", ex);@b@            }@b@          }@b@@b@          if ((arg != null) && (!(arg instanceof BeanMetadataElement)))@b@            return arg.getClass();@b@@b@          return method.getReturnType();@b@        }@b@        if (methodParameterType instanceof ParameterizedType) {@b@          ParameterizedType parameterizedType = (ParameterizedType)methodParameterType;@b@          Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();@b@          arrayOfType1 = actualTypeArguments; int l = arrayOfType1.length; for (i1 = 0; i1 < l; ++i1) { Type typeArg = arrayOfType1[i1];@b@            if (typeArg.equals(genericReturnType)) {@b@              if (arg instanceof Class) {@b@                return ((Class)arg);@b@              }@b@@b@              String className = null;@b@              if (arg instanceof String) {@b@                className = (String)arg;@b@              }@b@              else if (arg instanceof TypedStringValue) {@b@                TypedStringValue typedValue = (TypedStringValue)arg;@b@                String targetTypeName = typedValue.getTargetTypeName();@b@                if ((targetTypeName == null) || (Class.class.getName().equals(targetTypeName)))@b@                  className = typedValue.getValue();@b@              }@b@@b@              if (className != null) {@b@                try {@b@                  return ClassUtils.forName(className, classLoader);@b@                }@b@                catch (ClassNotFoundException ex) {@b@                  throw new IllegalStateException("Could not resolve class name [" + arg + "] for factory method argument", ex);@b@                }@b@@b@              }@b@@b@              return method.getReturnType();@b@            }@b@          }@b@@b@        }@b@@b@      }@b@@b@@b@    return method.getReturnType();@b@  }@b@@b@  private static class ObjectFactoryDelegatingInvocationHandler@b@    implements InvocationHandler, Serializable@b@  {@b@    private final ObjectFactory<?> objectFactory;@b@@b@    public ObjectFactoryDelegatingInvocationHandler(ObjectFactory<?> objectFactory)@b@    {@b@      this.objectFactory = objectFactory;@b@    }@b@@b@    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable@b@    {@b@      String methodName = method.getName();@b@      if (methodName.equals("equals"))@b@      {@b@        return Boolean.valueOf(proxy == args[0]);@b@      }@b@      if (methodName.equals("hashCode"))@b@      {@b@        return Integer.valueOf(System.identityHashCode(proxy));@b@      }@b@      if (methodName.equals("toString"))@b@        return this.objectFactory.toString();@b@      try@b@      {@b@        return method.invoke(this.objectFactory.getObject(), args);@b@      }@b@      catch (InvocationTargetException ex) {@b@        throw ex.getTargetException();@b@      }@b@    }@b@  }@b@}