1. return instantiateBean(beanName, mbd);

instantiateBean 使用无参构造实例化对象。
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#instantiateBean

  1. protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
  2. try {
  3. Object beanInstance;
  4. if (System.getSecurityManager() != null) {
  5. beanInstance = AccessController.doPrivileged(
  6. (PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, this),
  7. getAccessControlContext());
  8. } else {
  9. beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
  10. }
  11. BeanWrapper bw = new BeanWrapperImpl(beanInstance);
  12. initBeanWrapper(bw);
  13. return bw;
  14. } catch (Throwable ex) {
  15. throw new BeanCreationException(
  16. mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
  17. }
  18. }

获得实例化策略 getInstantiationStrategy 得到 CglibSubclassingInstantiationStrategy

  1. protected InstantiationStrategy getInstantiationStrategy() {
  2. return this.instantiationStrategy;
  3. }
  4. private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();

其继承关系如下:
image.png

看下接口 InstantiationStrategy 创建实例的三个策略

  1. // 不指定构造函数来创建实例
  2. Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner)
  3. throws BeansException;
  4. // 根据指定数构造创建实例
  5. Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
  6. Constructor<?> ctor, Object... args) throws BeansException;
  7. // 根据工厂方法创建实例
  8. Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
  9. @Nullable Object factoryBean, Method factoryMethod, Object... args)
  10. throws BeansException;

来到方法 instantiate。
org.springframework.beans.factory.support.SimpleInstantiationStrategy#instantiate

  1. @Override
  2. public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
  3. // Don't override the class with CGLIB if no overrides.
  4. // bd中是否包含了MethodOverrides的列表,这方法的列表由spring提供的lookup-method,replaced-method标签生成
  5. if (!bd.hasMethodOverrides()) {
  6. Constructor<?> constructorToUse;
  7. synchronized (bd.constructorArgumentLock) {
  8. // 在缓存中获取构造方法
  9. constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
  10. if (constructorToUse == null) {
  11. final Class<?> clazz = bd.getBeanClass();
  12. // 接口不可以实例化,抛出异常
  13. if (clazz.isInterface()) {
  14. throw new BeanInstantiationException(clazz, "Specified class is an interface");
  15. }
  16. try {
  17. // 安全机制的特权处理
  18. if (System.getSecurityManager() != null) {
  19. constructorToUse = AccessController.doPrivileged(
  20. (PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
  21. }
  22. else {
  23. // 获取声明的构造方法
  24. constructorToUse = clazz.getDeclaredConstructor();
  25. }
  26. // 缓存构造方法
  27. bd.resolvedConstructorOrFactoryMethod = constructorToUse;
  28. }
  29. catch (Throwable ex) {
  30. throw new BeanInstantiationException(clazz, "No default constructor found", ex);
  31. }
  32. }
  33. }
  34. // 反射生成对象
  35. return BeanUtils.instantiateClass(constructorToUse);
  36. }
  37. else {
  38. // Must generate CGLIB subclass.
  39. // 如果有MethodOverrides对象,需要使用cglib来进行代理
  40. return instantiateWithMethodInjection(bd, beanName, owner);
  41. }
  42. }

反射实例化对象

org.springframework.beans.BeanUtils#instantiateClass

  1. public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
  2. Assert.notNull(ctor, "Constructor must not be null");
  3. try {
  4. ReflectionUtils.makeAccessible(ctor);
  5. if (KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(ctor.getDeclaringClass())) {
  6. return KotlinDelegate.instantiateClass(ctor, args);
  7. }
  8. else {
  9. Class<?>[] parameterTypes = ctor.getParameterTypes();
  10. Assert.isTrue(args.length <= parameterTypes.length, "Can't specify more arguments than constructor parameters");
  11. Object[] argsWithDefaultValues = new Object[args.length];
  12. for (int i = 0 ; i < args.length; i++) {
  13. if (args[i] == null) {
  14. Class<?> parameterType = parameterTypes[i];
  15. argsWithDefaultValues[i] = (parameterType.isPrimitive() ? DEFAULT_TYPE_VALUES.get(parameterType) : null);
  16. }
  17. else {
  18. argsWithDefaultValues[i] = args[i];
  19. }
  20. }
  21. return ctor.newInstance(argsWithDefaultValues);
  22. }
  23. }
  24. catch (InstantiationException ex) {
  25. throw new BeanInstantiationException(ctor, "Is it an abstract class?", ex);
  26. }
  27. catch (IllegalAccessException ex) {
  28. throw new BeanInstantiationException(ctor, "Is the constructor accessible?", ex);
  29. }
  30. catch (IllegalArgumentException ex) {
  31. throw new BeanInstantiationException(ctor, "Illegal arguments for constructor", ex);
  32. }
  33. catch (InvocationTargetException ex) {
  34. throw new BeanInstantiationException(ctor, "Constructor threw exception", ex.getTargetException());
  35. }
  36. }

cglib生成代理对象

org.springframework.beans.factory.support.CglibSubclassingInstantiationStrategy#instantiateWithMethodInjection

  1. // cglib 生成代理对象
  2. protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
  3. return instantiateWithMethodInjection(bd, beanName, owner, null);
  4. }
  5. // 重载方法
  6. protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
  7. @Nullable Constructor<?> ctor, Object... args) {
  8. // Must generate CGLIB subclass...
  9. return new CglibSubclassCreator(bd, owner).instantiate(ctor, args);
  10. }
  11. // 实例化代理对象
  12. public Object instantiate(@Nullable Constructor<?> ctor, Object... args) {
  13. Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
  14. Object instance;
  15. if (ctor == null) {
  16. instance = BeanUtils.instantiateClass(subclass);
  17. }
  18. else {
  19. try {
  20. Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
  21. instance = enhancedSubclassConstructor.newInstance(args);
  22. }
  23. catch (Exception ex) {
  24. throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
  25. "Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex);
  26. }
  27. }
  28. // SPR-10785: set callbacks directly on the instance instead of in the
  29. // enhanced class (via the Enhancer) in order to avoid memory leaks.
  30. Factory factory = (Factory) instance;
  31. factory.setCallbacks(new Callback[] {NoOp.INSTANCE,
  32. new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
  33. new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
  34. return instance;
  35. }