Spring的IOC的源码解析(三)

在《Spring的IOC的源码解析(二)》中完成了BFPP和BPP的处理分析;这篇接着分bean的实例化。
在用bean工厂创建bean对象时,调用的是父类AbstractBeanFactory中提供的getBean的系列方法。往下,在AbstractAutowireCapableBeanFactory的createBean方法中,有下边一段代码,
try {
    // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
    Object bean = resolveBeforeInstantiation(beanName, mbdToUse); //看分析(1)
    if (bean != null) {
        return bean;
    }
}
catch (Throwable ex) {
    throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
            "BeanPostProcessor before instantiation of bean failed", ex);
}
try {
    Object beanInstance = doCreateBean(beanName, mbdToUse, args); //生成实例,看分析(2)
    if (logger.isDebugEnabled()) {
        logger.debug("Finished creating instance of bean '" + beanName + "'");
    }
    return beanInstance;
}

(1) 继续看 resolveBeforeInstantiation方法
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
    Object bean = null;
    if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
        // Make sure bean class is actually resolved at this point.
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { // !mbd.isSynthetic()默认是true,如果注册了 InstantiationAwareBeanPostProcessors类型的BPP,右侧表达式也是true
            Class targetType = determineTargetType(beanName, mbd);
            if (targetType != null) {
                bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                if (bean != null) {
                    bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                }
            }
        }
        mbd.beforeInstantiationResolved = (bean != null);
    }
    return bean;
}
mbd.isSynthetic()对于Pointcut 的bean来说是true的!
很明显,如果在这里就返回bean 是不可能的。
(2)下边看看bean的创建
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) { //如果是单例bean,从缓存获取
    instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
    instanceWrapper = createBeanInstance(beanName, mbd, args); //真正创建实例;继续看(3)
}
final Object bean = instanceWrapper.getWrappedInstance();
final Object bean = instanceWrapper.getWrappedInstance();
Class beanType = instanceWrapper.getWrappedClass(); //获取实例化类的类型
if (beanType != NullBean.class) {
    mbd.resolvedTargetType = beanType; //设置到mdb
}
synchronized (mbd.postProcessingLock) {
    if (!mbd.postProcessed) {
        try {
            applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); //调用MergedBeanDefinitionPostProcessor BPP处理
        }
        catch (Throwable ex) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    "Post-processing of merged bean definition failed", ex);
        }
        mbd.postProcessed = true;
    }
}
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); //默认允许处理循环引用;这个bool表达式表示:在默认情况下,如果单例bean已经在创建了的情况;这应该是循环引用场景下,又尝试初始化mbd
if (earlySingletonExposure) {
    if (logger.isDebugEnabled()) {
        logger.debug("Eagerly caching bean '" + beanName +
                "' to allow for resolving potential circular references");
    }
    addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); //为mbd设置工厂类
}
Object exposedObject = bean;
try {
    populateBean(beanName, mbd, instanceWrapper);//增强处理(10)
    exposedObject = initializeBean(beanName, exposedObject, mbd); //增强处理(10)
}

(3) 实例创建,策略有:factory method, constructor autowiring, or simple instantiation.
这里只要介绍3种:
if (mbd.getFactoryMethodName() != null)  {
return instantiateUsingFactoryMethod(beanName, mbd, args); //设置了工厂方法,使用工厂方法创建实例;参见(4)
}
if (autowireNecessary) {
    return autowireConstructor(beanName, mbd, null, null); //自动绑定构造方法;参见(5)
}
else {
    return instantiateBean(beanName, mbd); //普通创建方法;参见(6)
}

(4)工厂方法创建实例
工厂方法创建实例包括两种情况:指定了工厂类bean或者工厂方法就是需要创建实例的bean的static方法
最终调用的方法是:strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse);

(5)自动选择构造方法
根据调用getBean()时指定的参数类型或者配置在bean定义中的参数类型,自动选择构造方法,然后调用:
strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse);

(6)普通情况
调用instantiate(mbd, beanName, parent);parent是当前容器实例;

这里的strategy就是AbstractAutowireCapableBeanFactory类的instantiationStrategy属性:
InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();

初始化方法从CglibSubclassingInstantiationStrategy的父类SimpleInstantiationStrategy开始,先看instantiate(mbd, beanName, parent);
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
    // Don't override the class with CGLIB if no overrides.
    if (!bd.hasMethodOverrides()) { //不需要方法重载时,不需要用CGLIB
        Constructor constructorToUse;
         //这里省略掉的代码就是获取构造方法
        return BeanUtils.instantiateClass(constructorToUse); //创建实例;参见(7)
    }
    else { //用CGLIB实现子类
        // Must generate CGLIB subclass.
        return instantiateWithMethodInjection(bd, beanName, owner); //在子类中实现;参见(8)
    }
}

再来看strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,final Constructor ctor, @Nullable Object... args) {
    if (!bd.hasMethodOverrides()) {
        return (args != null ? BeanUtils.instantiateClass(ctor, args) : BeanUtils.instantiateClass(ctor)); //参看(7)
    }
    else {
        return instantiateWithMethodInjection(bd, beanName, owner, ctor, args); //CGLIB,在子类中实现 ;参见(8)
    }
}

(7) 创建实例,核心代码就是
try {
    ReflectionUtils.makeAccessible(ctor);
    return (KotlinDetector.isKotlinType(ctor.getDeclaringClass()) ?
            KotlinDelegate.instantiateClass(ctor, args) : ctor.newInstance(args));
}

(8) CGLIB怎么创建实例的?
return new CglibSubclassCreator(bd, owner).instantiate(ctor, args);
调用内部类是实现,看内部类的代码:
public Object instantiate(@Nullable Constructor ctor, @Nullable Object... args) {
    Class subclass = createEnhancedSubclass(this.beanDefinition); //参见(9)
    Object instance;
    if (ctor == null) {
        instance = BeanUtils.instantiateClass(subclass); //参见(7)
    }
    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; //直接在instance上设置Callbacks,而不是在enhancer对象上,是为了避免内存溢出
    factory.setCallbacks(new Callback[] {NoOp.INSTANCE,
            new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
            new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
    return instance; //返回生成的实例
}

(9) 获取增强子类
private Class createEnhancedSubclass(RootBeanDefinition beanDefinition) {
    Enhancer enhancer = new Enhancer(); //增强工具类
    enhancer.setSuperclass(beanDefinition.getBeanClass()); //设置父类
    enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE); //设置命名策略,是一个 SpringNamingPolicy对象
    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); //继承方法拦截处理,包括两个内部类: LookupOverrideMethodInterceptor ReplaceOverrideMethodInterceptor;后边直接在实例上设置callbacks
    return enhancer.createClass(); //创建增强类的Class对象
}

(10) BPP在这里是否能参与增强bean实例呢?方法的说明:applying factory callbacks as well as init methods and bean post processors,就是使用init方法,BPP,工厂回调方法初始化实例。
populateBean方法:
boolean continueWithPropertyPopulation = true;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { //如果设置了 InstantiationAwareBeanPostProcessors
    for (BeanPostProcessor bp : getBeanPostProcessors()) {
        if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { //执行实例化后处理方法
                continueWithPropertyPopulation = false;
                break;
            }
        }
    }
}
精简的代码:
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
    invokeAwareMethods(beanName, bean); //绑定方法,主要为Aware子类设置beanName beanClassLoader beanFactory
    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) { //默认 Synthetic==false; 表示不是组装类;所以这个bool表达式是true的
        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); //执行BPP的前处理方法
    }
    try {
        invokeInitMethods(beanName, wrappedBean, mbd); //调用init方法初始化
    }
    if (mbd == null || !mbd.isSynthetic()) {
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); // 执行BPP的后处理方法
    }
    return wrappedBean;
}
下边先看看容器中BPP的情况。
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
    Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
    this.beanPostProcessors.remove(beanPostProcessor);
    this.beanPostProcessors.add(beanPostProcessor);
    if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
        this.hasInstantiationAwareBeanPostProcessors = true;
    }
    if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
        this.hasDestructionAwareBeanPostProcessors = true;
    }
}
由addBeanPostProcessor可知,如果bean定义解析过程中设置了InstantiationAwareBeanPostProcessor类型的BPP,那么hasInstantiationAwareBeanPostProcessors()将返回true。
那么什么情况下会设置InstantiationAwareBeanPostProcessor类型的BPP呢?
在AbstractApplicationContext. prepareBeanFactory(beanFactory);方法中会设置如下3个BPP:
ApplicationContextAwareProcessor
ApplicationListenerDetector
LoadTimeWeaverAwareProcessor
但是这3个都不是 InstantiationAwareBeanPostProcessor类型的;

其他的呢?
AbstractApplicationContext.refresh()方法执行到下边这一行时,实际的调用过程是把所有 BeanPostProcessor的Bean全部实例化;然后每一个都调用 addBeanPostProcessor方法;
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);

由自动代理bean的注册过程可知,如果我们配置了 或者 aspectj-autoproxy>或者annotation-driven>标签,那么一定会注册一个 InstantiationAwareBeanPostProcessor类型的bean:
id="org.springframework.aop.config.internalAutoProxyCreator"
class= AnnotationAwareAspectJAutoProxyCreator或者 AspectJAwareAdvisorAutoProxyCreator或者 InfrastructureAdvisorAutoProxyCreator
其中 AnnotationAwareAspectJAutoProxyCreator是 AspectJAwareAdvisorAutoProxyCreator的子类,且3个类的父类继承体系也是一样的;
总的来说,这三个标签都能开启spring的aop功能。

先看看这3个公共的BPP是怎么执行的?
ApplicationContextAwareProcessor的前处理方法的核心逻辑在下边的方法中:
private void invokeAwareInterfaces(Object bean) {
    if (bean instanceof Aware) {
        if (bean instanceof EnvironmentAware) {
            ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
        }
        if (bean instanceof EmbeddedValueResolverAware) {
            ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
        }
        if (bean instanceof ResourceLoaderAware) {
            ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
        }
        if (bean instanceof ApplicationEventPublisherAware) {
            ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
        }
        if (bean instanceof MessageSourceAware) {
            ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
        }
        if (bean instanceof ApplicationContextAware) {
            ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
        }
    }
}
后处理方法直接返回原对象;

ApplicationListenerDetector处理 ApplicationListener bean ,但是逻辑简单,这里先忽略;

LoadTimeWeaverAwareProcessor的前处理方法如下:
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    if (bean instanceof LoadTimeWeaverAware) { //只处 LoadTimeWeaverAware类型的bean
        LoadTimeWeaver ltw = this.loadTimeWeaver;
        if (ltw == null) {
            Assert.state(this.beanFactory != null,
                    "BeanFactory required if no LoadTimeWeaver explicitly specified");
            ltw = this.beanFactory.getBean( ConfigurableApplicationContext.LOAD_TIME_WEAVER_BEAN_NAME, LoadTimeWeaver.class);
           //这里要获取id=" loadTimeWeaver"的bean,根据load-time-weaver标签的解析讲解知道:要么配置了load-time-weaver标签要么手动配置了 id=" loadTimeWeaver"的bean;否则,这里获取对象会失败
        }
        ((LoadTimeWeaverAware) bean).setLoadTimeWeaver(ltw); //这一句就是 LoadTimeWeaverAwareProcessor的意义所在,为所有 LoadTimeWeaverAware类型的对象设置LTW weaver
    }
    return bean;
}
后处理方法直接返回原对象;

再看AOP自动代理类的BPP对bean的代理处理过程:
populateBean方法执行父类 AbstractAutoProxyCreator中postProcessAfterInstantiation方法,如下:
public boolean postProcessAfterInstantiation(Object bean, String beanName) {
    return true;
}
但是什么都没有做!

initializeBean方法执行 父类 AbstractAutoProxyCreator中 postProcessBeforeInitialization ,但是 前处理方法直接返回原对象;
再看执行 postProcessAfterInitialization 方法,代码如下:
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) throws BeansException {
    if (bean != null) { //bean是创建的对象,bean!==null为true
        Object cacheKey = getCacheKey(bean.getClass(), beanName); //如果beanName是null或者长度为0,就返回beanClass;否则,如果是FactoryBean就返回"&"+beanName,否则返回beanName
        if (!this.earlyProxyReferences.contains(cacheKey)) { //
            return wrapIfNecessary(bean, beanName, cacheKey); //生成增强的子类的代理对象,主要就是处理bean配置的interceptors
        }
    }
    return bean;
}

AbstractAutoProxyCreator类的 wrapIfNecessary方法:
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
    if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) { //如果已经存在,就直接返回
        return bean;
    }
    if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) { //如果已经存在,就直接返回
        return bean;
    }
    if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) { //判断是否是基本的类型或者是否是可以跳过的bean;参见(11)
        this.advisedBeans.put(cacheKey, Boolean.FALSE);
        return bean;
    }
    // Create proxy if we have advice.
    Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null); //获取能够处理目标类的advisor,这里的bean.getClass()方法返回的是当前对象的类,需要说明的是:如果是第一个BPP,那么就是原始指定的被代理类,否则,这里得到的就是上一次代理对象对应的类;逻辑见《AOP Proxy 对象创建过程》(1)
    if (specificInterceptors != DO_NOT_PROXY) {//存在需要处理的advisor时,使用代理
        this.advisedBeans.put(cacheKey, Boolean.TRUE);//有advisor的bean对象,value=true
        Object proxy = createProxy( bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean)); // Create an AOP proxy for the given bean,分析见《 AOP Proxy 对象创建过程》 (2)
        this.proxyTypes.put(cacheKey, proxy.getClass());
        return proxy;
    }
    this.advisedBeans.put(cacheKey, Boolean.FALSE);//没有advisor的bean对象,value=false
    return bean;
}

(11) 如下类型或者这些类型的子类的对象被称为基本类型
Advice.class
Pointcut.class
Advisor.class
AopInfrastructureBean.class

shouldSkip()在 AspectJAwareAdvisorAutoProxyCreator 中实现,逻辑 就是beanName如果是advisor切面的名字就跳过,也就是不处理切面bean;

接着就是代理对象的处理过程了,请看《 AOP Proxy 对象创建过程 》。



你可能感兴趣的:(源码阅读,JAVA,web应用)