bean实例化底层采用Java反射机制,但Spring根据框架需要提供了更多的增强功能。
类关系图
InstantiationStrategy:接口-定义了创建RootBeanDefinition对应bean实例方法
SimpleInstantiationStrategy:简单bean的实例化处理。实现了InstantiationStrategy,但不支持方法注入。
CglibSubclassingInstantiationStrategy:继承于SimpleInstantiationStrategy,主要实现有方法注入bean的实例化。是BeanFactory的默认实例化bean的构建器。
AbstractClassGenerator:CGLIB实例化器使用到的工具抽象类。除了缓存生成的类以提高性能外,它还提供了钩子,用于自定义ClassLoader、生成的类的名称以及生成前应用的转换
Enhancer:增强类,生成用于方法拦截的动态子类。动态生成的子类覆盖超类的非最终方法,并具有回调到用户定义的拦截器实现的钩子。
BeanUtils:封装JavaBeans实例化方法的抽象类(全部是静态方法),包括实例化bean、检查bean属性类型、复制bean属性等。
ReflectionUtils:spring封装的用于处理类反射API和处理反射异常的实用程序类。
SimpleInstantiationStrategy
instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner)
bean实例化入口
@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)
动态实例化类入口
// 过渡方法
@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;
}
内部类CglibSubclassCreator.createEnhancedSubclass
创建增强的动态子类
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();
}
}
内部类MethodOverrideCallbackFilter
CGLIB回调过滤器,只要针对方法拦截行为。实现了CallbackFilter接口,主要就是accept方法。
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());
}
}
内部类LookupOverrideMethodInterceptor
CGLIB MethodInterceptor重写方法,用在容器中查找的bean的实现返回。
主要实现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());
}
}
}
内部类ReplaceOverrideMethodInterceptor
CGLIB MethodInterceptor重写方法,用对泛型MethodReplacer的调用替换它们。
主要实现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)
实例化类。
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());
}
}