Spring AOP 原理

Spring 大约 13322 字

版本

spring-aspects-5.3.13

步骤

  1. @EnableAspectJAutoProxy开启AOP功能
  2. @EnableAspectJAutoProxy会注入AnnotationAwareAspectJAutoProxyCreator后置处理器
  3. IOC容器创建时会在registerBeanPostProcessors注册并创建AnnotationAwareAspectJAutoProxyCreator
  4. finishBeanFactoryInitialization阶段在beaninitializeBeanapplyBeanPostProcessorsAfterInitialization会回调postProcessAfterInitialization,从而拦截bean,且返回一个代理对象。
  5. 执行目标方法,CglibAopProxyintercept方法。

@EnableAspectJAutoProxy

@EnableAspectJAutoProxy注解主要作用是注册AnnotationAwareAspectJAutoProxyCreator

@Import(AspectJAutoProxyRegistrar.class)
public @interface EnableAspectJAutoProxy {
}

导入AspectJAutoProxyRegistrar组件

class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        // 注册
        AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);

        // 配置属性,不重要
        AnnotationAttributes enableAspectJAutoProxy = AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
        if (enableAspectJAutoProxy != null) {
            if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {
                AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
            }
            if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {
                AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
            }
        }
    }
}

注册keyinternalAutoProxyCreatorAnnotationAwareAspectJAutoProxyCreator定义信息到BeanDefinitionMap

public abstract class AopConfigUtils {

    public static final String AUTO_PROXY_CREATOR_BEAN_NAME = "org.springframework.aop.config.internalAutoProxyCreator";

    @Nullable
    public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) {
        // 往下调用
        return registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry, null);
    }

    @Nullable
    public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, @Nullable Object source) {
        // 往下调用
        return registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);
    }

    // 注册 AnnotationAwareAspectJAutoProxyCreator
    @Nullable
    private static BeanDefinition registerOrEscalateApcAsRequired(Class<?> cls, BeanDefinitionRegistry registry, @Nullable Object source) {
        // 注册 AnnotationAwareAspectJAutoProxyCreator 到 BeanDefinitionMap 中
        RootBeanDefinition beanDefinition = new RootBeanDefinition(cls);
        beanDefinition.setSource(source);
        beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE);
        beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
        registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition);
        return beanDefinition;
    }
}

AnnotationAwareAspectJAutoProxyCreator

继承关系,最底下为最顶层类。

- AnnotationAwareAspectJAutoProxyCreator
    - AspectJAwareAdvisorAutoProxyCreator
        - AbstractAdvisorAutoProxyCreator
            - AbstractAutoProxyCreator
                - implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware

AnnotationAwareAspectJAutoProxyCreator会在所有Bean创建之前会拦截。

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

        // resolveBeforeInstantiation 给后置处理器一个机会返回一个代理对象
        Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
        if (bean != null) {
            return bean;
        }
        // 没有代理对象,则真正去创建对象
        Object beanInstance = doCreateBean(beanName, mbdToUse, args);
        return beanInstance;
    }

    @Nullable
    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.
            // hasInstantiationAwareBeanPostProcessors 判断是否有实现了 InstantiationAwareBeanPostProcessor 接口的对象
            if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
                // 决定代理对象的类型
                Class<?> targetType = determineTargetType(beanName, mbd);
                if (targetType != null) {
                    // 调用实例创建前回调,如果创建了代理对象则 bean 不为空
                    bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                    if (bean != null) {
                        // 回调 bean 已经被初始化完成了
                        bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                    }
                }
            }
        }
        return bean;
    }

    @Nullable
    protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
        // 遍历执行回调 postProcessBeforeInstantiation
        for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
            Object result = bp.postProcessBeforeInstantiation(beanClass, beanName);
            if (result != null) {
                return result;
            }
        }
        return null;
    }

}

AbstractAutoProxyCreator中处理postProcessBeforeInstantiation回调(基本不做处理)和postProcessAfterInitialization回调(生成代理对象)。

findCandidateAdvisors中获取所有切入点。

public class AnnotationAwareAspectJAutoProxyCreator extends AspectJAwareAdvisorAutoProxyCreator {
    @Override
    protected boolean isInfrastructureClass(Class<?> beanClass) {
        return (super.isInfrastructureClass(beanClass) ||
                (this.aspectJAdvisorFactory != null && this.aspectJAdvisorFactory.isAspect(beanClass)));
    }
}

public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator {
    @Override
    protected boolean shouldSkip(Class<?> beanClass, String beanName) {
        // TODO: Consider optimization by caching the list of the aspect names
        // 获取增强器的集合 
        // 实际类型是 InstantiationModelAwarePointcutAdvisorImpl
        List<Advisor> candidateAdvisors = findCandidateAdvisors();
        for (Advisor advisor : candidateAdvisors) {
            if (advisor instanceof AspectJPointcutAdvisor &&
                    ((AspectJPointcutAdvisor) advisor).getAspectName().equals(beanName)) {
                return true;
            }
        }
        return super.shouldSkip(beanClass, beanName);
    }
}

public abstract class AbstractAspectJAdvisorFactory implements AspectJAdvisorFactory {
    @Override
    public boolean isAspect(Class<?> clazz) {
        return (hasAspectAnnotation(clazz) && !compiledByAjc(clazz));
    }

    private boolean hasAspectAnnotation(Class<?> clazz) {
        // 是否标注了 @Aspect 注解
        return (AnnotationUtils.findAnnotation(clazz, Aspect.class) != null);
    }
}

public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
        Object cacheKey = getCacheKey(beanClass, beanName);

        if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
            // advisedBeans 保存了需要增加的 bean
            if (this.advisedBeans.containsKey(cacheKey)) {
                return null;
            }
            // 调用 AnnotationAwareAspectJAutoProxyCreator 中的 isInfrastructureClass 判断 bean 是否是基础类型的,先调用子类实现的,再由子类 super 调用
            // 调用 AnnotationAwareAspectJAutoProxyCreator 的 shouldSkip  方法
            if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
                this.advisedBeans.put(cacheKey, Boolean.FALSE);
                return null;
            }
        }

        // 自定义 TargetSource
        // 省略了...

        // postProcessBeforeInstantiation 不做处理
        return null;
    }

    protected boolean isInfrastructureClass(Class<?> beanClass) {
        // 是不是 Advice Pointcut Advisor AopInfrastructureBean 类型
        boolean retVal = Advice.class.isAssignableFrom(beanClass) ||
                Pointcut.class.isAssignableFrom(beanClass) ||
                Advisor.class.isAssignableFrom(beanClass) ||
                AopInfrastructureBean.class.isAssignableFrom(beanClass);
        return retVal;
    }

    @Override
    public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
        if (bean != null) {
            Object cacheKey = getCacheKey(bean.getClass(), beanName);
            if (this.earlyProxyReferences.remove(cacheKey) != bean) {
                // 生成代理对象
                return wrapIfNecessary(bean, beanName, cacheKey);
            }
        }
        return bean;
    }

    protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
        // 如果有切入点就生成代理对象
        Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
        if (specificInterceptors != DO_NOT_PROXY) {
            this.advisedBeans.put(cacheKey, Boolean.TRUE);
            // 生成代理对象
            Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
            this.proxyTypes.put(cacheKey, proxy.getClass());
            return proxy;
        }
        this.advisedBeans.put(cacheKey, Boolean.FALSE);
        return bean;
    }

    protected Object createProxy(Class<?> beanClass, @Nullable String beanName, @Nullable Object[] specificInterceptors, TargetSource targetSource) {
        // 创建代理工厂
        ProxyFactory proxyFactory = new ProxyFactory();
        // 构建切入点数组
        Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
        proxyFactory.addAdvisors(advisors);

        return proxyFactory.getProxy(classLoader);
    }
}

DefaultAopProxyFactorycreateAopProxy决定是使用JdkDynamicAopProxy还是ObjenesisCglibAopProxy

public class ProxyFactory extends ProxyCreatorSupport {
    public Object getProxy(@Nullable ClassLoader classLoader) {
        return createAopProxy().getProxy(classLoader);
    }
}

public class ProxyCreatorSupport extends AdvisedSupport {

    private AopProxyFactory aopProxyFactory;

    public ProxyCreatorSupport() {
        this.aopProxyFactory = new DefaultAopProxyFactory();
    }

    public AopProxyFactory getAopProxyFactory() {
        return this.aopProxyFactory;
    }

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

}

public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
    @Override
    public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
        if (!NativeDetector.inNativeImage() && (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config))) {
            Class<?> targetClass = config.getTargetClass();

            if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
                return new JdkDynamicAopProxy(config);
            }
            return new ObjenesisCglibAopProxy(config);
        }
        else {
            return new JdkDynamicAopProxy(config);
        }
    }
}

完整调用栈

createAopProxy:54, DefaultAopProxyFactory (org.springframework.aop.framework)
createAopProxy:105, ProxyCreatorSupport (org.springframework.aop.framework)
getProxy:110, ProxyFactory (org.springframework.aop.framework)
createProxy:478, AbstractAutoProxyCreator (org.springframework.aop.framework.autoproxy)
wrapIfNecessary:342, AbstractAutoProxyCreator (org.springframework.aop.framework.autoproxy)
postProcessAfterInitialization:291, AbstractAutoProxyCreator (org.springframework.aop.framework.autoproxy)
applyBeanPostProcessorsAfterInitialization:455, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
initializeBean:1808, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
doCreateBean:620, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBean:542, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
lambda$doGetBean$0:335, AbstractBeanFactory (org.springframework.beans.factory.support)
getObject:-1, 466505482 (org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$34)
getSingleton:234, DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
doGetBean:333, AbstractBeanFactory (org.springframework.beans.factory.support)
getBean:208, AbstractBeanFactory (org.springframework.beans.factory.support)
preInstantiateSingletons:944, DefaultListableBeanFactory (org.springframework.beans.factory.support)
finishBeanFactoryInitialization:918, AbstractApplicationContext (org.springframework.context.support)
refresh:583, AbstractApplicationContext (org.springframework.context.support)
<init>:93, AnnotationConfigApplicationContext (org.springframework.context.annotation)
main:15, TestAOP (com.example.learn)
阅读 53 · 发布于 2021-12-24

————        END        ————

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批