Spring - AOP 源码阅读笔记 : 织入目标对象

in TCEH Java

前言

上一篇文章中介绍了解析切面在 postProcessBeforeInitialization 方法中被触发,本篇要介绍的切面织入目标对象在 postProcessAfterInitialization 方法中被触发。

postProcessAfterInitialization() 方法

AbstractAutoProxyCreator#postProcessAfterInitialization

    @Override
    public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
        if (bean != null) {
            // 若是来自 FactoryBean 的子类或实现类,则返回 &beanName , 否则返回 beanName
            Object cacheKey = getCacheKey(bean.getClass(), beanName);
            // 该 Bean 尚未处理
            if (this.earlyProxyReferences.remove(cacheKey) != bean) {
                return wrapIfNecessary(bean, beanName, cacheKey);
            }
        }
        return bean;
    }

wrapIfNecessary() 方法

    protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
        // 目标源缓存包含当前 Bean 的话,直接返回,后续再处理
        if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
            return bean;
        }
        // advisedBeans 用于存储不可代理的 bean 或已经代理过的 Bean,
        // 值为 false 说明不支持代理,值为 true 说明已经代理过了
        if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
            return bean;
        }
        // 判断当前 bean 是否可以被代理,然后存入 advisedBeans ,这两个方法在上一篇文章中介绍过
        if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
            this.advisedBeans.put(cacheKey, Boolean.FALSE);
            return bean;
        }

        // Create proxy if we have advice.
        // 匹配到当前 Bean 的 advice
        Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
        // 当前 Bean 有 Advisor
        if (specificInterceptors != DO_NOT_PROXY) {
            // 存的值为 TRUE , 用于表示已经代理了
            this.advisedBeans.put(cacheKey, Boolean.TRUE);
            // 创建代理对象
            Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
            // 缓存代理过的类型
            this.proxyTypes.put(cacheKey, proxy.getClass());
            return proxy;
        }

        // 当前 Bean 没有 advice
        this.advisedBeans.put(cacheKey, Boolean.FALSE);
        return bean;
    }

getAdvicesAndAdvisorsForBean() 方法

    @Override
    @Nullable
    protected Object[] getAdvicesAndAdvisorsForBean(
            Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {

        List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
        if (advisors.isEmpty()) {
            return DO_NOT_PROXY;
        }
        return advisors.toArray();
    }

findEligibleAdvisors() 方法

    protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
        // 前面已经扫描过切面了,该方法会直接从缓存里取
        List<Advisor> candidateAdvisors = findCandidateAdvisors();
        // 查找当前类匹配的 advisor
        List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
        // 添加一个默认的 advisor
        extendAdvisors(eligibleAdvisors);
        if (!eligibleAdvisors.isEmpty()) {
            eligibleAdvisors = sortAdvisors(eligibleAdvisors);
        }
        return eligibleAdvisors;
    }

findAdvisorsThatCanApply() 方法

    protected List<Advisor> findAdvisorsThatCanApply(
            List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {
        // 使用 ThreadLocal 存储当前要代理 Bean 的名称。避免并发导致数据出现错乱
        ProxyCreationContext.setCurrentProxiedBeanName(beanName);
        try {
            // 继续往下查找
            return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
        }
        finally {
            ProxyCreationContext.setCurrentProxiedBeanName(null);
        }
    }

findAdvisorsThatCanApply() 方法

AopUtils#findAdvisorsThatCanApply

    public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
        if (candidateAdvisors.isEmpty()) {
            return candidateAdvisors;
        }
        // 存储匹配到 Advisor
        List<Advisor> eligibleAdvisors = new ArrayList<>();
        for (Advisor candidate : candidateAdvisors) {
            // IntroductionAdvisor 只能应用于类级别的拦截。不常见,不深入
            if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
                eligibleAdvisors.add(candidate);
            }
        }
        boolean hasIntroductions = !eligibleAdvisors.isEmpty();
        for (Advisor candidate : candidateAdvisors) {
            if (candidate instanceof IntroductionAdvisor) {
                // already processed
                continue;
            }
            // 判断当前类是否能匹配到 advice ,可以的话,添加到 eligibleAdvisors 中
            if (canApply(candidate, clazz, hasIntroductions)) {
                eligibleAdvisors.add(candidate);
            }
        }
        return eligibleAdvisors;
    }

createProxy() 方法

    protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
            @Nullable Object[] specificInterceptors, TargetSource targetSource) {

        if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
            AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
        }

        // 创建代理工厂
        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.copyFrom(this);
        // 是否直接代理目标类
        if (!proxyFactory.isProxyTargetClass()) {
            if (shouldProxyTargetClass(beanClass, beanName)) {
                proxyFactory.setProxyTargetClass(true);
            }
            else {
                evaluateProxyInterfaces(beanClass, proxyFactory);
            }
        }
        // 整合匹配到的 Advisor 和通用的 Advisor 
        Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
        proxyFactory.addAdvisors(advisors);
        proxyFactory.setTargetSource(targetSource);
        // 自定义代理工厂
        customizeProxyFactory(proxyFactory);
        // 禁止修改
        proxyFactory.setFrozen(this.freezeProxy);
        if (advisorsPreFiltered()) {
            proxyFactory.setPreFiltered(true);
        }
        // 往下走
        return proxyFactory.getProxy(getProxyClassLoader());
    }

getProxy() 方法

    public Object getProxy(@Nullable ClassLoader classLoader) {
        return createAopProxy().getProxy(classLoader);
    }

createAopProxy() 方法

    protected final synchronized AopProxy createAopProxy() {
        if (!this.active) {
            activate();
        }
        return getAopProxyFactory().createAopProxy(this);
    }

createAopProxy() 方法

    @Override
    public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
        // Optimize 是否应执行积极的优化,默认 false
        // ProxyTargetClass 在 AopAutoConfiguration 中指定,默认 true
        // hasNoUserSuppliedProxyInterfaces 仅实现了 SpringProxy 接口或没有实现接口时为 true
        if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
            Class<?> targetClass = config.getTargetClass();
            if (targetClass == null) {
                throw new AopConfigException("TargetSource cannot determine target class: " +
                        "Either an interface or a target is required for proxy creation.");
            }
            // 接口或者 Proxy 类型,才用 JDK 动态代理
            if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
                return new JdkDynamicAopProxy(config);
            }
            return new ObjenesisCglibAopProxy(config);
        }
        else {
            return new JdkDynamicAopProxy(config);
        }
    }

总结