Let’s learn SF framework series 5.9-spring-Beans-bean instance creation together

The bottom layer of bean instantiation uses Java reflection mechanism, but Spring provides more enhanced functions according to the needs of the framework.

Class diagram

Insert image description here

InstantiationStrategy : Interface - defines the method for creating bean instances corresponding to RootBeanDefinition.
SimpleInstantiationStrategy : Instantiation processing of simple beans. InstantiationStrategy is implemented, but method injection is not supported.
CglibSubclassingInstantiationStrategy : Inherited from SimpleInstantiationStrategy, it mainly implements the instantiation of method-injected beans. Is the BeanFactory's default instantiated bean builder.

AbstractClassGenerator : Tool abstract class used by CGLIB instantiator. In addition to caching generated classes to improve performance, it also provides hooks for customizing the ClassLoader, the name of the generated class, and the transformations applied before generation. Enhancer: Enhanced
class , generating dynamic subclasses for method interception. Dynamically generated subclasses override the superclass's non-final methods and have hooks that call back to user-defined interceptor implementations.

BeanUtils : An abstract class that encapsulates JavaBeans instantiation methods (all static methods), including instantiating beans, checking bean attribute types, copying bean attributes, etc.

ReflectionUtils : A utility class encapsulated by spring for handling class reflection APIs and handling reflection exceptions.

SimpleInstantiationStrategy

instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner)

bean instantiation entry

	@Override
	public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
    
    
		// Don't override the class with CGLIB if no overrides.
		if (!bd.hasMethodOverrides()) {
    
    
		// 无重写方法bean的实例化
			Constructor<?> constructorToUse;
			synchronized (bd.constructorArgumentLock) {
    
    
				constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
				if (constructorToUse == null) {
    
    
					//没有指定bean的构建器,就取Class默认构建器
					final Class<?> clazz = bd.getBeanClass();
					if (clazz.isInterface()) {
    
    
						throw new BeanInstantiationException(clazz, "Specified class is an interface");
					}
					try {
    
    
						// 调用Java类的获取Class默认构建器
						constructorToUse = clazz.getDeclaredConstructor();
						bd.resolvedConstructorOrFactoryMethod = constructorToUse;
					}
					catch (Throwable ex) {
    
    
						throw new BeanInstantiationException(clazz, "No default constructor found", ex);
					}
				}
			}
			// 构建bean实例
			return BeanUtils.instantiateClass(constructorToUse);
		}
		else {
    
    
			// 有重写方法bean的实例化(见CglibSubclassingInstantiationStrategy)
			return instantiateWithMethodInjection(bd, beanName, owner);
		}
	}

CglibSubclassingInstantiationStrategy

instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner)

Dynamic instantiation class entry

	// 过渡方法
	@Override
	protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
    
    
		return instantiateWithMethodInjection(bd, beanName, owner, null);
	}

	@Override
	protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
			@Nullable Constructor<?> ctor, Object... args) {
    
    
		// 调用内部类方法:CglibSubclassCreator.instantiate
		return new CglibSubclassCreator(bd, owner).instantiate(ctor, args);
	}

内部类CglibSubclassCreator.instantiate(@Nullable Constructor<?> ctor, Object… args)

		public Object instantiate(@Nullable Constructor<?> ctor, Object... args) {
    
    
			// 创建增强的动态子类
			Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
			Object instance;
			if (ctor == null) {
    
    
				// 如果是构造函数为空,则使用默认的构造函数创建实例,注意这里创建的实例是bean的增强子类的
				instance = BeanUtils.instantiateClass(subclass);
			}
			else {
    
    
				try {
    
    
					// 根据参数类型从增强子类的class中获取对应的增强子类构造函数
					Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
					// 通过增强子类构造函数,创建bean的增强子类的实例对象
					instance = enhancedSubclassConstructor.newInstance(args);
				}
				catch (Exception ex) {
    
    
					throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
							"Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex);
				}
			}
			// 设置回调被代理类的方法
			// SPR-10785: set callbacks directly on the instance instead of in the
			// enhanced class (via the Enhancer) in order to avoid memory leaks.
			Factory factory = (Factory) instance;
			factory.setCallbacks(new Callback[] {
    
    NoOp.INSTANCE,
					new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
					new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
			return instance;
		}

Internal classCglibSubclassCreator.createEnhancedSubclass

Create enhanced dynamic subclasses

		public Class<?> createEnhancedSubclass(RootBeanDefinition beanDefinition) {
    
    
			// 创建Enhancer类 
			Enhancer enhancer = new Enhancer();
			// beanDefinition为增强子类的父Classs
			enhancer.setSuperclass(beanDefinition.getBeanClass());
			// 设置命令策略-实例化
			enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
			//使用临时的类加载器
			enhancer.setAttemptLoad(true);
			// 设置类加载器(将应用程序ClassLoader作为为当前线程上下文ClassLoader)
			if (this.owner instanceof ConfigurableBeanFactory cbf) {
    
    
				ClassLoader cl = cbf.getBeanClassLoader();
				enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(cl));
			}
			// 设置代理器(回调方法),用于获取使用哪种cglib的interceptor来增强子类
			enhancer.setCallbackFilter(new MethodOverrideCallbackFilter(beanDefinition));
			// 设置回调类型
			enhancer.setCallbackTypes(CALLBACK_TYPES);
			return enhancer.createClass();
		}
	}

Inner class MethodOverrideCallbackFilter

CGLIB callback filter only intercepts behavior for methods. Implemented the CallbackFilter interface, mainly the accept method.

	private static class MethodOverrideCallbackFilter extends CglibIdentitySupport implements CallbackFilter {
    
    

		private static final Log logger = LogFactory.getLog(MethodOverrideCallbackFilter.class);

		public MethodOverrideCallbackFilter(RootBeanDefinition beanDefinition) {
    
    
			super(beanDefinition);
		}

		@Override
		public int accept(Method method) {
    
    
			// 从beanDefinition中获取方法的MethodOverride
			MethodOverride methodOverride = getBeanDefinition().getMethodOverrides().getOverride(method);
			if (logger.isTraceEnabled()) {
    
    
				logger.trace("MethodOverride for " + method + ": " + methodOverride);
			}
			if (methodOverride == null) {
    
    
				//不存在
				return PASSTHROUGH;
			}
			else if (methodOverride instanceof LookupOverride) {
    
    
				//可按bean名称或bean类型(基于方法声明的返回类型)查找对象的Override方法。对应内部类LookupOverrideMethodInterceptor
				return LOOKUP_OVERRIDE;
			}
			else if (methodOverride instanceof ReplaceOverride) {
    
    
				//非LookupOverride类型的其它重载方法。对应内部类ReplaceOverrideMethodInterceptor
				return METHOD_REPLACER;
			}
			throw new UnsupportedOperationException("Unexpected MethodOverride subclass: " +
					methodOverride.getClass().getName());
		}
	}

Inner classLookupOverrideMethodInterceptor

CGLIB MethodInterceptor override method, returned with the implementation of the bean found in the container.
Mainly implements MethodInterceptor.intercept.

	private static class LookupOverrideMethodInterceptor extends CglibIdentitySupport implements MethodInterceptor {
    
    

		private final BeanFactory owner;

		public LookupOverrideMethodInterceptor(RootBeanDefinition beanDefinition, BeanFactory owner) {
    
    
			super(beanDefinition);
			this.owner = owner;
		}

		@Override
		public Object intercept(Object obj, Method method, Object[] args, MethodProxy mp) throws Throwable {
    
    
			//获取LookupOverride 
			// Cast is safe, as CallbackFilter filters are used selectively.
			LookupOverride lo = (LookupOverride) getBeanDefinition().getMethodOverrides().getOverride(method);
			Assert.state(lo != null, "LookupOverride not found");
			Object[] argsToUse = (args.length > 0 ? args : null);  // if no-arg, don't insist on args at all
			if (StringUtils.hasText(lo.getBeanName())) {
    
    
				// 按beanName从容器中获取bean返回
				Object bean = (argsToUse != null ? this.owner.getBean(lo.getBeanName(), argsToUse) :
						this.owner.getBean(lo.getBeanName()));
				// Detect package-protected NullBean instance through equals(null) check
				return (bean.equals(null) ? null : bean);
			}
			else {
    
    
				//没有beanName,按照返回类型返回bean
				// Find target bean matching the (potentially generic) method return type
				ResolvableType genericReturnType = ResolvableType.forMethodReturnType(method);
				return (argsToUse != null ? this.owner.getBeanProvider(genericReturnType).getObject(argsToUse) :
						this.owner.getBeanProvider(genericReturnType).getObject());
			}
		}
	}

Inner classReplaceOverrideMethodInterceptor

CGLIB MethodInterceptor overrides methods, replacing them with calls to the generic MethodReplacer.
Mainly implements MethodInterceptor.intercept.

	private static class ReplaceOverrideMethodInterceptor extends CglibIdentitySupport implements MethodInterceptor {
    
    

		private final BeanFactory owner;

		public ReplaceOverrideMethodInterceptor(RootBeanDefinition beanDefinition, BeanFactory owner) {
    
    
			super(beanDefinition);
			this.owner = owner;
		}

		@Override
		public Object intercept(Object obj, Method method, Object[] args, MethodProxy mp) throws Throwable {
    
    
			// 获取对应的ReplacedOverride
			ReplaceOverride ro = (ReplaceOverride) getBeanDefinition().getMethodOverrides().getOverride(method);
			Assert.state(ro != null, "ReplaceOverride not found");
			// 获取对应的MethodReplacer
			// TODO could cache if a singleton for minor performance optimization
			MethodReplacer mr = this.owner.getBean(ro.getMethodReplacerBeanName(), MethodReplacer.class);
			// 调用MethodReplacer的reimplement方法获取结果
			return mr.reimplement(obj, method, args);
		}
	}

BeanUtils

instantiateClass(Constructor ctor, Object… args)

Instantiate the class.

	public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
    
    
		// 类构建器不能为空
		Assert.notNull(ctor, "Constructor must not be null");
		try {
    
    
			// 设置类构建器是可访问的
			ReflectionUtils.makeAccessible(ctor);
			if (KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(ctor.getDeclaringClass())) {
    
    
				// kotlin java (Kotlin作为Android应用程序开的第二种官方编程语言)
				return KotlinDelegate.instantiateClass(ctor, args);
			}
			else {
    
    
				// 获得类构建器参数数量
				int parameterCount = ctor.getParameterCount();
				Assert.isTrue(args.length <= parameterCount, "Can't specify more arguments than constructor parameters");
				if (parameterCount == 0) {
    
    
					// 无参构建器直接new新实例
					return ctor.newInstance();
				}
				// 获得类构建器参数类型
				Class<?>[] parameterTypes = ctor.getParameterTypes();
				// 把传入的参数值赋给对应的参数
				Object[] argsWithDefaultValues = new Object[args.length];
				for (int i = 0 ; i < args.length; i++) {
    
    
					if (args[i] == null) {
    
    
						Class<?> parameterType = parameterTypes[i];
						argsWithDefaultValues[i] = (parameterType.isPrimitive() ? DEFAULT_TYPE_VALUES.get(parameterType) : null);
					}
					else {
    
    
						argsWithDefaultValues[i] = args[i];
					}
				}
				// 有参构建新实例
				return ctor.newInstance(argsWithDefaultValues);
			}
		}
		catch (InstantiationException ex) {
    
    
			throw new BeanInstantiationException(ctor, "Is it an abstract class?", ex);
		}
		catch (IllegalAccessException ex) {
    
    
			throw new BeanInstantiationException(ctor, "Is the constructor accessible?", ex);
		}
		catch (IllegalArgumentException ex) {
    
    
			throw new BeanInstantiationException(ctor, "Illegal arguments for constructor", ex);
		}
		catch (InvocationTargetException ex) {
    
    
			throw new BeanInstantiationException(ctor, "Constructor threw exception", ex.getTargetException());
		}
	}

Guess you like

Origin blog.csdn.net/davidwkx/article/details/131053503