Spring源码12. DefaultListableBeanFactory载入解析和注册Bean

目录

1. 注册BeanDefinition
2. 预初始化单例Bean
    2.1 AbstractBeanFactory获取或者创建Bean实例
    2.2 AbstractAutowireCapableBeanFactory#createBean创建bean
3. SimpleInstantiationStrategy#instantiate 实例化策略
    3.1 CglibSubclassingInstantiationStrategy cglib实例化策略

DefaultListableBeanFactory类继承关系

1. 注册BeanDefinition

首先验证BeanDefinition, 验证通过之后, 判断BeanDefinition是否已经存在

  • 存在的话, 判断是否重写和优先级, 然后将BeanDefinition维护到beanDefinitionMap中
  • 不存在的话, 直接维护到beanDefinitionNames中
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
        implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
    
    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
            throws BeanDefinitionStoreException {

        Assert.hasText(beanName, "Bean name must not be empty");
        Assert.notNull(beanDefinition, "BeanDefinition must not be null");

        if (beanDefinition instanceof AbstractBeanDefinition) {
            try {
                //验证beanDefinition
                //方法重写和bean重名
                ((AbstractBeanDefinition) beanDefinition).validate();
            }
            catch (BeanDefinitionValidationException ex) {
                throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
                        "Validation of bean definition failed", ex);
            }
        }
        
        //bean定义已经存在
        BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
        if (existingDefinition != null) {
            //bean定义不允许重写,则抛出异常
            if (!isAllowBeanDefinitionOverriding()) {
                throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
            }
            else if (existingDefinition.getRole() < beanDefinition.getRole()) {
                //BeanDefinition的role
                //ROLE_APPLICATION = 0,  整个application重要组成部分, 通常是用户自定义Bean的ROLE
                //ROLE_SUPPORT = 1,  一个大的配置的支撑部分, springboot引入的外部BeanDefinition
                //ROLE_INFRASTRUCTURE = 2, springboot底层的BeanDefinition
                if (logger.isInfoEnabled()) {
                    logger.info("Overriding user-defined bean definition for bean '" + beanName +
                            "' with a framework-generated bean definition: replacing [" +
                            existingDefinition + "] with [" + beanDefinition + "]");
                }
            }
            else if (!beanDefinition.equals(existingDefinition)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Overriding bean definition for bean '" + beanName +
                            "' with a different definition: replacing [" + existingDefinition +
                            "] with [" + beanDefinition + "]");
                }
            }
            else {
                if (logger.isTraceEnabled()) {
                    logger.trace("Overriding bean definition for bean '" + beanName +
                            "' with an equivalent definition: replacing [" + existingDefinition +
                            "] with [" + beanDefinition + "]");
                }
            }
            //将新的BeanDefinition放入到map中
            this.beanDefinitionMap.put(beanName, beanDefinition);
        }
        else {
            //已经开始创建bean
            if (hasBeanCreationStarted()) {
                //保证beanDefinitionNames线程安全
                synchronized (this.beanDefinitionMap) {
                    //重新赋值beanDefinitionNames
                    this.beanDefinitionMap.put(beanName, beanDefinition);
                    List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
                    updatedDefinitions.addAll(this.beanDefinitionNames);
                    updatedDefinitions.add(beanName);
                    this.beanDefinitionNames = updatedDefinitions;
                    //beanName已经被手动维护了
                    if (this.manualSingletonNames.contains(beanName)) {
                        //则更新manualSingletonNames
                        //使用注册的BeanDefinition替换手动维护的beanDefinition
                        Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
                        updatedSingletons.remove(beanName);
                        this.manualSingletonNames = updatedSingletons;
                    }
                }
            }
            else {
                //bean还没有开始创建
                //仍然处于BeanDefinition注册阶段
                this.beanDefinitionMap.put(beanName, beanDefinition);
                this.beanDefinitionNames.add(beanName);
                this.manualSingletonNames.remove(beanName);
            }
            this.frozenBeanDefinitionNames = null;
        }

        if (existingDefinition != null || containsSingleton(beanName)) { 
            //如果beanDefinition已经存在
            //递归重置BeanDefinition以及其父BeanDefinition
            resetBeanDefinition(beanName);
        }
    }
}

2. 预初始化单例Bean

refreshContext()刷新应用上下文 finishBeanFactoryInitialization方法中, 执行了beanFactory.preInstantiateSingletons方法, 预初始化了非延时加载bean

首先从beanDefinitionNames中获取BeanDefinition列表, 递归将parent和child BeanDefinition合并成一个RootBeanDefinition, 然后判断BeanDefinition是否为factoryBean

  • 如果是factoryBean, 先判断是否立即加载, 然后通过getBean()方法获取或生成bean
  • 如果不是factoryBean, 直接通过getBean()方法获取或生成bean
    如果beanSmartInitializingSingleton的子类, 那么在初始化之后执行SmartInitializingSingleton#afterSingletonsInstantiated方法
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
        implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
    
    //预初始化单例Bean
    @Override
    public void preInstantiateSingletons() throws BeansException {
        if (logger.isTraceEnabled()) {
            logger.trace("Pre-instantiating singletons in " + this);
        }

        //开辟一个新的List, 存储this.beanDefinitionNames
        List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

        //触发单例bean的实例化
        for (String beanName : beanNames) {
            //xml定义的bean中有parent属性,
            //getMergedLocalBeanDefinition会递归将parent和child BeanDefinition合并成一个RootBeanDefinition
            RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
            //非抽象类, 单例的, 非延迟加载的才执行代码
            if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
                //FactoryBean工厂bean, 并不是直接返回一个Bean, 而是通过getObject()方法, 返回一个bean实例
                if (isFactoryBean(beanName)) {
                    //获取factoryBean
                    Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                    if (bean instanceof FactoryBean) {
                        final FactoryBean<?> factory = (FactoryBean<?>) bean;
                        //立即加载
                        boolean isEagerInit;
                        if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                            isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
                                            ((SmartFactoryBean<?>) factory)::isEagerInit,
                                    getAccessControlContext());
                        }
                        else {
                            isEagerInit = (factory instanceof SmartFactoryBean &&
                                    ((SmartFactoryBean<?>) factory).isEagerInit());
                        }
                        if (isEagerInit) {
                            //如果立即加载
                            //那么调用getBean方法
                            getBean(beanName);
                        }
                    }
                }
                else {
                    //不是工厂Bean
                    //立即调用getBean方法
                    getBean(beanName);
                }
            }
        }

        //触发SmartInitializingSingleton类型bean实例化之后的回调
        for (String beanName : beanNames) {
            Object singletonInstance = getSingleton(beanName);
            if (singletonInstance instanceof SmartInitializingSingleton) {
                //SmartInitializingSingleton的子类
                final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                        //回调
                        smartSingleton.afterSingletonsInstantiated();
                        return null;
                    }, getAccessControlContext());
                }
                else {
                    //回调
                    smartSingleton.afterSingletonsInstantiated();
                }
            }
        }
    }
}
2.1 AbstractBeanFactory获取或者创建Bean实例

先判断是否为factoryBean, 如果是的话, 那么会调用其getObject方法, 获取bean, 之后检查bean是否循环依赖, 如果当前beanFactory中获取不到bean, 会尝试递归从父factory中加载bean, 之后把bean标记为已创建, 然后先去实例化依赖的bean, 最后判断bean的scope并实例化bean

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {

    //获取Bean实例
    @Override
    public Object getBean(String name) throws BeansException {
        return doGetBean(name, null, null, false);
    }
    
    //实际获取Bean实例的方法
    protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
            @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

        final String beanName = transformedBeanName(name);
        Object bean;

        //是否手工注册的单例Bean
        Object sharedInstance = getSingleton(beanName);
        if (sharedInstance != null && args == null) {
            //打印日志
            if (logger.isTraceEnabled()) {
                if (isSingletonCurrentlyInCreation(beanName)) {
                    logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
                            "' that is not fully initialized yet - a consequence of a circular reference");
                }
                else {
                    logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
                }
            }
            //如果是factoryBean的话, 那么会调用其getObject方法, 获取bean
            //不是factoryBean的话, 直接返回当前bean
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
        }

        else {
            //检查是否循环依赖
            if (isPrototypeCurrentlyInCreation(beanName)) {
                throw new BeanCurrentlyInCreationException(beanName);
            }

            //检查当前beanFactory中是否包含bean
            BeanFactory parentBeanFactory = getParentBeanFactory();
            if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
                //当前beanFactory中不包含bean
                //递归从parent beanFactory中获取
                String nameToLookup = originalBeanName(name);
                if (parentBeanFactory instanceof AbstractBeanFactory) {
                    return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                            nameToLookup, requiredType, args, typeCheckOnly);
                }
                else if (args != null) {
                    //父beanFactory 获取bean
                    return (T) parentBeanFactory.getBean(nameToLookup, args);
                }
                else if (requiredType != null) {
                    // 父beanFactory 获取bean
                    return parentBeanFactory.getBean(nameToLookup, requiredType);
                }
                else {
                    //父beanFactory 获取bean
                    return (T) parentBeanFactory.getBean(nameToLookup);
                }
            }

            if (!typeCheckOnly) {
                //标记bean已创建
                markBeanAsCreated(beanName);
            }

            try {
                final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                checkMergedBeanDefinition(mbd, beanName, args);

                // 先加载被依赖的bean
                String[] dependsOn = mbd.getDependsOn();
                if (dependsOn != null) {
                    for (String dep : dependsOn) {
                        if (isDependent(beanName, dep)) {
                            //...
                        }
                        registerDependentBean(dep, beanName);
                        try {
                            //递归实例化被依赖的bean
                            getBean(dep);
                        }
                        catch (NoSuchBeanDefinitionException ex) {
                            //...
                        }
                    }
                }

                // 创建bean实例
                if (mbd.isSingleton()) {
                    sharedInstance = getSingleton(beanName, () -> {
                        try {
                            return createBean(beanName, mbd, args);
                        }
                        catch (BeansException ex) {
                            //...
                        }
                    });
                    //如果是factoryBean, 那么通过其getObject()方法获取bean
                    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                }

                else if (mbd.isPrototype()) {
                    //beanDefinition的scope设置为prototype
                    //每次都获取新的实例
                    Object prototypeInstance = null;
                    try {
                        //bean创建之前的回调
                        beforePrototypeCreation(beanName);
                        //创建bean
                        prototypeInstance = createBean(beanName, mbd, args);
                    }
                    finally {
                         //bean创建之后的回调
                        afterPrototypeCreation(beanName);
                    }
                    //如果是factoryBean, 那么调用其getObject方法获取bean
                    bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                }

                else {
                    //获取scope
                    String scopeName = mbd.getScope();
                    final Scope scope = this.scopes.get(scopeName);
                    if (scope == null) {
                        //...
                    }
                    try {
                        Object scopedInstance = scope.get(beanName, () -> {
                           //bean创建之前的回调
                            beforePrototypeCreation(beanName);
                            try {
                                //创建bean
                                return createBean(beanName, mbd, args);
                            }
                            finally {
                            //bean创建之后的回调
                                afterPrototypeCreation(beanName);
                            }
                        });
                        bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                    }
                    catch (IllegalStateException ex) {
                        //...
                    }
                }
            }
            catch (BeansException ex) {
                //创建出现异常, 清空缓存
                cleanupAfterBeanCreationFailure(beanName);
                throw ex;
            }
        }

        // requiredType和要创建bean类型一致
        if (requiredType != null && !requiredType.isInstance(bean)) {
            try {
                //类型不一致进行转换
                T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
                if (convertedBean == null) {
                    throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
                }
                return convertedBean;
            }
            catch (TypeMismatchException ex) {
                //...
            }
        }
        //返回bean
        return (T) bean;
    }
}
2.2 AbstractAutowireCapableBeanFactory#createBean

先解析beanClass, 尝试重写方法, 执行InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation方法, 可以使用代理生成新的bean

创建bean的过程中, 先执行MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition, 然后执行BeanPostProcessor#postProcessBeforeInitialization, 再判断要采取的实例化策略, 一种是反射, 另一种是cglib动态代理, 然后使用策略实例化bean, 再执行BeanPostProcessor#postProcessAfterInitialization, 对bean进行增强处理

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
        implements AutowireCapableBeanFactory {
    
    //创建bean
    @Override
    protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
            throws BeanCreationException {

        if (logger.isTraceEnabled()) {
            logger.trace("Creating instance of bean '" + beanName + "'");
        }
        RootBeanDefinition mbdToUse = mbd;

        // 解析BeanClass
        Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
        if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
            //复制BeanDefinition
            mbdToUse = new RootBeanDefinition(mbd);
            mbdToUse.setBeanClass(resolvedClass);
        }

        //方法重写
        try {
            mbdToUse.prepareMethodOverrides();
        }
        catch (BeanDefinitionValidationException ex) {
            //...
        }

        try {
            //执行InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation方法
            Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
            if (bean != null) {
                return bean;
            }
        }
        catch (Throwable ex) {
            //...
        }

        try {
            //创建bean
            Object beanInstance = doCreateBean(beanName, mbdToUse, args);
            if (logger.isTraceEnabled()) {
                logger.trace("Finished creating instance of bean '" + beanName + "'");
            }
            return beanInstance;
        }
        catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
            //...
        }
        catch (Throwable ex) {
            //...
        }
    }
    
    //实际创建bean的方法
    protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
            throws BeanCreationException {

        // 初始化bean
        BeanWrapper instanceWrapper = null;
        if (mbd.isSingleton()) {
            instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
        }
        //bean不是factoryBean
        if (instanceWrapper == null) {
            //创建bean实例
            //使用对应的策略模式简单的创建新实例
            instanceWrapper = createBeanInstance(beanName, mbd, args);
        }
        final Object bean = instanceWrapper.getWrappedInstance();
        Class<?> beanType = instanceWrapper.getWrappedClass();
        if (beanType != NullBean.class) {
            mbd.resolvedTargetType = beanType;
        }

        synchronized (mbd.postProcessingLock) {
            if (!mbd.postProcessed) {
                try {
                    //执行MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition方法
                    applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                }
                catch (Throwable ex) {
                    //...
                }
                mbd.postProcessed = true;
            }
        }

        //循环依赖处理
        boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
                isSingletonCurrentlyInCreation(beanName));
        if (earlySingletonExposure) {
            if (logger.isTraceEnabled()) {
                logger.trace("Eagerly caching bean '" + beanName +
                        "' to allow for resolving potential circular references");
            }
            addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
        }

        // 实例化bean
        Object exposedObject = bean;
        try {
            //执行InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation
            //并处理autowireByName和autowireByType
            //然后处理InstantiationAwareBeanPostProcessor#postProcessProperties
            populateBean(beanName, mbd, instanceWrapper);
            //实例化bean
            exposedObject = initializeBean(beanName, exposedObject, mbd);
        }
        catch (Throwable ex) {
            //...
        }

        if (earlySingletonExposure) {
            Object earlySingletonReference = getSingleton(beanName, false);
            if (earlySingletonReference != null) {
                if (exposedObject == bean) {
                    exposedObject = earlySingletonReference;
                }
                else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                    //依赖bean
                    String[] dependentBeans = getDependentBeans(beanName);
                    Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                    for (String dependentBean : dependentBeans) {
                        if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                            actualDependentBeans.add(dependentBean);
                        }
                    }
                    if (!actualDependentBeans.isEmpty()) {
                        //...
                    }
                }
            }
        }

        // 注册bean销毁方法
        try {
            registerDisposableBeanIfNecessary(beanName, bean, mbd);
        }
        catch (BeanDefinitionValidationException ex) {
            //...
        }

        return exposedObject;
    }
    
    //创建bean实例的方法
    protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
        // 解析beanClass
        Class<?> beanClass = resolveBeanClass(mbd, beanName);

        if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
        }

        //使用Supplier#get()获取实例
        Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
        if (instanceSupplier != null) {
            return obtainFromSupplier(instanceSupplier, beanName);
        }

        //设置了factoryMethodName
        //自定义factory生成bean实例
        if (mbd.getFactoryMethodName() != null) {
            return instantiateUsingFactoryMethod(beanName, mbd, args);
        }

        //简单实例化bean
        boolean resolved = false;
        boolean autowireNecessary = false;
        if (args == null) {
            synchronized (mbd.constructorArgumentLock) {
                if (mbd.resolvedConstructorOrFactoryMethod != null) {
                    resolved = true;
                    autowireNecessary = mbd.constructorArgumentsResolved;
                }
            }
        }
        if (resolved) {
            if (autowireNecessary) {
                //构造函数解析
                //调用ConstructorResolver#autowireConstructor
                //先解析构造函数, 然后使用实例化策略实例化对象
                return autowireConstructor(beanName, mbd, null, null);
            }
            else {
                //简单实例化
                //使用实例化策略实例化对象
                return instantiateBean(beanName, mbd);
            }
        }

        //判断是否通过构造函数实例化
        Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
        if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
                mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
            //构造函数实例化
            //传入了参数
            return autowireConstructor(beanName, mbd, ctors, args);
        }

        ctors = mbd.getPreferredConstructors();
        if (ctors != null) {
            return autowireConstructor(beanName, mbd, ctors, null);
        }

        //无须特殊处理, 简单实例化bean
        return instantiateBean(beanName, mbd);
    }
    
    //使用默认构造函数实例化bean
    protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
        try {
            Object beanInstance;
            final BeanFactory parent = this;
            if (System.getSecurityManager() != null) {
                beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
                        getInstantiationStrategy().instantiate(mbd, beanName, parent),
                        getAccessControlContext());
            }
            else {
                //获取bean初始化策略
                //然后调用CglibSubclassingInstantiationStrategy#instantiate实例化bean
                beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
            }
            BeanWrapper bw = new BeanWrapperImpl(beanInstance);
            initBeanWrapper(bw);
            return bw;
        }
        catch (Throwable ex) {
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
        }
    }
    
    //继续初始化bean实例, 设置Aware对象, 设置init方法
    //执行BeanPostProcessor#postProcessBeforeInitialization方法
    //执行BeanPostProcessor#postProcessAfterInitialization方法
    protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
        //如果是Aware类型的bean
        //那么在bean中注入相应的对象
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                invokeAwareMethods(beanName, bean);
                return null;
            }, getAccessControlContext());
        }
        else {
            invokeAwareMethods(beanName, bean);
        }

        Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
            wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
        }

        try {
            //如果是InitializingBean类型的bean
            //那么执行afterPropertiesSet方法
            invokeInitMethods(beanName, wrappedBean, mbd);
        }
        catch (Throwable ex) {
            throw new BeanCreationException(
                    (mbd != null ? mbd.getResourceDescription() : null),
                    beanName, "Invocation of init method failed", ex);
        }
        if (mbd == null || !mbd.isSynthetic()) {
            //执行BeanPostProcessor#postProcessAfterInitialization方法
            wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }

        return wrappedBean;
    }
}

3. SimpleInstantiationStrategy#instantiate

默认策略, 实例化对象, 如果有Override方法, 那么使用cglib实例化对象, 否则使用反射

public class SimpleInstantiationStrategy implements InstantiationStrategy {
    @Override
    public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
        //没有Override方法, 那么不使用cglib
        if (!bd.hasMethodOverrides()) {
            Constructor<?> constructorToUse;
            synchronized (bd.constructorArgumentLock) {
                constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
                if (constructorToUse == null) {
                    final Class<?> clazz = bd.getBeanClass();
                    if (clazz.isInterface()) {
                        //接口肯定有override方法
                        throw new BeanInstantiationException(clazz, "Specified class is an interface");
                    }
                    try {
                        if (System.getSecurityManager() != null) {
                            constructorToUse = AccessController.doPrivileged(
                                    (PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
                        }
                        else {
                            constructorToUse = clazz.getDeclaredConstructor();
                        }
                        bd.resolvedConstructorOrFactoryMethod = constructorToUse;
                    }
                    catch (Throwable ex) {
                        throw new BeanInstantiationException(clazz, "No default constructor found", ex);
                    }
                }
            }
            //通过反射实例化对象
            return BeanUtils.instantiateClass(constructorToUse);
        }
        else {
            //有Override方法,那么使用cglib
            return instantiateWithMethodInjection(bd, beanName, owner);
        }
    }
}
3.1 CglibSubclassingInstantiationStrategy#instantiateWithMethodInjection

cglib实例化对象

//Cglib实例化策略
public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationStrategy {   

    @Override
    protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
            @Nullable Constructor<?> ctor, Object... args) {

        //内部类CglibSubclassCreator实例化对象
        return new CglibSubclassCreator(bd, owner).instantiate(ctor, args);
    }
    
    //静态内部类
    private static class CglibSubclassCreator {
        //实例化
        public Object instantiate(@Nullable Constructor<?> ctor, Object... args) {
            Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
            Object instance;
            if (ctor == null) {
                //构造函数为空
                //反射实例化
                instance = BeanUtils.instantiateClass(subclass);
            }
            else {
                try {
                    //通过构造函数实例化
                    Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
                    instance = enhancedSubclassConstructor.newInstance(args);
                }
                catch (Exception ex) {
                    throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
                            "Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex);
                }
            }
            Factory factory = (Factory) instance;
            //设置回调
            factory.setCallbacks(new Callback[] {NoOp.INSTANCE,
                    new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
                    new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
            return instance;
        }
        
        //cglib创建类
        private Class<?> createEnhancedSubclass(RootBeanDefinition beanDefinition) {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(beanDefinition.getBeanClass());
            enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
            if (this.owner instanceof ConfigurableBeanFactory) {
                ClassLoader cl = ((ConfigurableBeanFactory) this.owner).getBeanClassLoader();
                enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(cl));
            }
            enhancer.setCallbackFilter(new MethodOverrideCallbackFilter(beanDefinition));
            enhancer.setCallbackTypes(CALLBACK_TYPES);
            //创建类
            return enhancer.createClass();
        }
    }
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,590评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,808评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,151评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,779评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,773评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,656评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,022评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,678评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,038评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,756评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,411评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,005评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,973评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,053评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,495评论 2 343

推荐阅读更多精彩内容

  • 作者: 一字马胡 转载标志 【2017-12-29】 更新日志 日期更新内容备注2017-12-29创建分析文档...
    一字马胡阅读 12,077评论 2 32
  • 在前面的文章中已经讲解了IOC容器的创建和Bean的注册,将XML文件中的信息封装成了BeanDefinition...
    九点半的马拉阅读 286评论 0 0
  • 之前就IOC的原理及使用有了一定的认识,作为Spring核心特性之一,IOC是很有必要重点掌握的。这次沉淀将会开启...
    天羽天阅读 494评论 0 4
  • 亲爱的老爸: 你好吗? 老妈订了好吃的手工点心,真的不错呢,就是贵了点哈哈。老妈看着我吃的开心,自己也很高兴。 下...
    老爸我很想你阅读 162评论 0 0
  • 1.创建数据透视表 (1)数据透视表的适用范围 EXCEL数据清单、数据库、文本文件、其他关系型数据文件 (2)数...
    羽萱_9423阅读 273评论 0 0