博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
AOP流程分析
阅读量:7039 次
发布时间:2019-06-28

本文共 19041 字,大约阅读时间需要 63 分钟。

1. 注册AnnotationAwareAspectJAutoProxyCreator

@EnableAspectJAutoProxy --> @Import(AspectJAutoProxyRegistrar.class) --> 注册AnnotationAwareAspectJAutoProxyCreator后处理器

public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {    ...    @Override    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {        if (bean != null) {            Object cacheKey = getCacheKey(bean.getClass(), beanName);            if (!this.earlyProxyReferences.contains(cacheKey)) {                return wrapIfNecessary(bean, beanName, cacheKey);            }        }        return bean;    }    protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {        ...        // 非Advice、Pointcut、Advisor、AopInfrastructureBean类型,且无@Aspect注解        if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {            this.advisedBeans.put(cacheKey, Boolean.FALSE);            return bean;        }        Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);        if (specificInterceptors != DO_NOT_PROXY) {            ...            Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));            ...            return proxy;        }        ...    }    protected Object createProxy(Class
beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) { ... ProxyFactory proxyFactory = new ProxyFactory(); ... Advisor[] advisors = buildAdvisors(beanName, specificInterceptors); for (Advisor advisor : advisors) { proxyFactory.addAdvisor(advisor); } ... return proxyFactory.getProxy(getProxyClassLoader()); } ...}

 

2. 扫描Advisor(Advice)

--> AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean

--> AbstractAdvisorAutoProxyCreator.findEligibleAdvisors

public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator {    ...    protected List
findEligibleAdvisors(Class
beanClass, String beanName) { // 获取所有Advisor(Advice),排序如下:@Around -> @Before -> @After -> @AfterReturning -> @AfterThrowing -> @Around -> @Before -> ... List
candidateAdvisors = findCandidateAdvisors(); List
eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName); // 适配Advisor(Advice) extendAdvisors(eligibleAdvisors); if (!eligibleAdvisors.isEmpty()) { // 局部排序:@AfterThrowing -> @AfterThrowing -> @After -> @Around -> @Before -> @AfterThrowing -> ... eligibleAdvisors = sortAdvisors(eligibleAdvisors); } return eligibleAdvisors; } ...}

--> findCandidateAdvisors

public class AnnotationAwareAspectJAutoProxyCreator extends AspectJAwareAdvisorAutoProxyCreator {    ...    private AspectJAdvisorFactory aspectJAdvisorFactory;    private BeanFactoryAspectJAdvisorsBuilder aspectJAdvisorsBuilder;    @Override    protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {        super.initBeanFactory(beanFactory);        if (this.aspectJAdvisorFactory == null) {            this.aspectJAdvisorFactory = new ReflectiveAspectJAdvisorFactory(beanFactory);        }        this.aspectJAdvisorsBuilder = new BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory, this.aspectJAdvisorFactory);    }    @Override    protected List
findCandidateAdvisors() { List
advisors = super.findCandidateAdvisors(); advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors()); return advisors; } ...}

--> BeanFactoryAspectJAdvisorsBuilderAdapter.buildAspectJAdvisors

public class BeanFactoryAspectJAdvisorsBuilder {    ...    private final AspectJAdvisorFactory advisorFactory; // ReflectiveAspectJAdvisorFactory    ...    public List
buildAspectJAdvisors() { List
aspectNames = this.aspectBeanNames; // 无缓存 if (aspectNames == null) { synchronized (this) { ... if (aspectNames == null) { List
advisors = new LinkedList
(); ... String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, Object.class, true, false); for (String beanName : beanNames) { ... Class
beanType = this.beanFactory.getType(beanName); ... if (this.advisorFactory.isAspect(beanType)) { ... if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) { // 单实例 MetadataAwareAspectInstanceFactory factory = new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName); List
classAdvisors = this.advisorFactory.getAdvisors(factory); ... advisors.addAll(classAdvisors); } else { // 多实例 ... MetadataAwareAspectInstanceFactory factory = new PrototypeAspectInstanceFactory(this.beanFactory, beanName); ... advisors.addAll(this.advisorFactory.getAdvisors(factory)); } } } ... return advisors; } } } // 有缓存 ... } ...}

--> ReflectiveAspectJAdvisorFactory.getAdvisors

public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFactory implements Serializable {    ...    @Override    public List
getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory) { Class
aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass(); ... List
advisors = new LinkedList
(); for (Method method : getAdvisorMethods(aspectClass)) { // 按方法上的注解排序:@Around -> @Before -> @After -> @AfterReturning -> @AfterThrowing Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, advisors.size(), aspectName); if (advisor != null) { advisors.add(advisor); } } ... return advisors; } @Override public Advisor getAdvisor(Method candidateAdviceMethod, MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrderInAspect, String aspectName) { ... AspectJExpressionPointcut expressionPointcut = getPointcut(candidateAdviceMethod, aspectInstanceFactory.getAspectMetadata().getAspectClass()); if (expressionPointcut == null) { return null; } return new InstantiationModelAwarePointcutAdvisorImpl(expressionPointcut, candidateAdviceMethod, this, aspectInstanceFactory, declarationOrderInAspect, aspectName); } public Advice getAdvice(Method candidateAdviceMethod, AspectJExpressionPointcut expressionPointcut, MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrder, String aspectName) { ... AspectJAnnotation
aspectJAnnotation = AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod); AbstractAspectJAdvice springAdvice; switch (aspectJAnnotation.getAnnotationType()) { case AtBefore: springAdvice = new AspectJMethodBeforeAdvice(candidateAdviceMethod, expressionPointcut, aspectInstanceFactory); break; case AtAfter: springAdvice = new AspectJAfterAdvice(candidateAdviceMethod, expressionPointcut, aspectInstanceFactory); break; case AtAfterReturning: springAdvice = new AspectJAfterReturningAdvice(candidateAdviceMethod, expressionPointcut, aspectInstanceFactory); ... break; case AtAfterThrowing: springAdvice = new AspectJAfterThrowingAdvice(candidateAdviceMethod, expressionPointcut, aspectInstanceFactory); ... break; case AtAround: springAdvice = new AspectJAroundAdvice(candidateAdviceMethod, expressionPointcut, aspectInstanceFactory); break; case AtPointcut: return null; default: ... } ... return springAdvice; } ...}

--> new InstantiationModelAwarePointcutAdvisorImpl

class InstantiationModelAwarePointcutAdvisorImpl implements InstantiationModelAwarePointcutAdvisor, AspectJPrecedenceInformation, Serializable {    ...    public InstantiationModelAwarePointcutAdvisorImpl(AspectJExpressionPointcut declaredPointcut, Method aspectJAdviceMethod, AspectJAdvisorFactory aspectJAdvisorFactory,            MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrder, String aspectName) {        ...        private Advice instantiatedAdvice;        ...        if (aspectInstanceFactory.getAspectMetadata().isLazilyInstantiated()) {            ...        }        else {            ...            this.instantiatedAdvice = instantiateAdvice(this.declaredPointcut);        }    }    private Advice instantiateAdvice(AspectJExpressionPointcut pcut) {        return this.aspectJAdvisorFactory.getAdvice(this.aspectJAdviceMethod, pcut, this.aspectInstanceFactory, this.declarationOrder, this.aspectName);    }    ...}

3. 创建代理

--> ProxyFactory.getProxy --> ProxyCreatorSupport.createAopProxy --> DefaultAopProxyFactory.createAopProxy

public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {    @Override    public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {        if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {            ...            return new ObjenesisCglibAopProxy(config); // CGLIB代理        }        else {            return new JdkDynamicAopProxy(config); // JDK代理        }    }    ...}

--> JDK代理

final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {    ...    protected final AdvisedSupport advised; // ProxyFactory    ...    @Override    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {        ...        try {            ...            List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);            if (chain.isEmpty()) {                ...            }            else {                invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);                retVal = invocation.proceed();            }            ...            return retVal;        }        ...    }    ...}

--> CGLIB代理

class CglibAopProxy implements AopProxy, Serializable {    ...    protected final AdvisedSupport advised; // ProxyFactory    ...    private Callback[] getCallbacks(Class
rootClass) throws Exception { ... if (isStatic && isFrozen) { Method[] methods = rootClass.getMethods(); ... for (int x = 0; x < methods.length; x++) { List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(methods[x], rootClass); fixedCallbacks[x] = new FixedChainStaticTargetInterceptor(chain, this.advised.getTargetSource().getTarget(), this.advised.getTargetClass()); ... } ... } ... } ... private static class FixedChainStaticTargetInterceptor implements MethodInterceptor, Serializable { ... @Override public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { MethodInvocation invocation = new CglibMethodInvocation(proxy, this.target, method, args, this.targetClass, this.adviceChain, methodProxy); Object retVal = invocation.proceed(); ... return retVal; } } private static class CglibMethodInvocation extends ReflectiveMethodInvocation { ... } ...}

4. 创建拦截器链

--> ProxyFactory.getInterceptorsAndDynamicInterceptionAdvice

public class AdvisedSupport extends ProxyConfig implements Advised {    ...    AdvisorChainFactory advisorChainFactory = new DefaultAdvisorChainFactory();    ...    public List getInterceptorsAndDynamicInterceptionAdvice(Method method, Class
targetClass) { ... if (cached == null) { cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(this, method, targetClass); ... } return cached; } ...}
public class DefaultAdvisorChainFactory implements AdvisorChainFactory, Serializable {    @Override    public List getInterceptorsAndDynamicInterceptionAdvice(Advised config, Method method, Class
targetClass) { ... AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance(); // DefaultAdvisorAdapterRegistry for (Advisor advisor : config.getAdvisors()) { if (advisor instanceof PointcutAdvisor) { PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor; if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) { MethodInterceptor[] interceptors = registry.getInterceptors(advisor); MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher(); if (MethodMatchers.matches(mm, method, actualClass, hasIntroductions)) { if (mm.isRuntime()) { for (MethodInterceptor interceptor : interceptors) { interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm)); } } else { interceptorList.addAll(Arrays.asList(interceptors)); } } } } ... } return interceptorList; } ...}
public class DefaultAdvisorAdapterRegistry implements AdvisorAdapterRegistry, Serializable {    private final List
adapters = new ArrayList
(3); public DefaultAdvisorAdapterRegistry() { registerAdvisorAdapter(new MethodBeforeAdviceAdapter()); registerAdvisorAdapter(new AfterReturningAdviceAdapter()); registerAdvisorAdapter(new ThrowsAdviceAdapter()); } ... @Override public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException { List
interceptors = new ArrayList
(3); Advice advice = advisor.getAdvice(); if (advice instanceof MethodInterceptor) { interceptors.add((MethodInterceptor) advice); } for (AdvisorAdapter adapter : this.adapters) { if (adapter.supportsAdvice(advice)) { interceptors.add(adapter.getInterceptor(advisor)); } } ... return interceptors.toArray(new MethodInterceptor[interceptors.size()]); } @Override public void registerAdvisorAdapter(AdvisorAdapter adapter) { this.adapters.add(adapter); }}

5. 调用拦截器链

--> ReflectiveMethodInvocation.proceed

public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Cloneable {    ...    protected final List
interceptorsAndDynamicMethodMatchers; ... @Override public Object proceed() throws Throwable { if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) { return invokeJoinpoint(); } Object interceptorOrInterceptionAdvice = this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex); if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) { ... } else { return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this); } } protected Object invokeJoinpoint() throws Throwable { return AopUtils.invokeJoinpointUsingReflection(this.target, this.method, this.arguments); } ...}

6. 五大通知(拦截器)

public class AspectJAroundAdvice extends AbstractAspectJAdvice implements MethodInterceptor, Serializable {    ...    @Override    public Object invoke(MethodInvocation mi) throws Throwable {        ...        ProxyMethodInvocation pmi = (ProxyMethodInvocation) mi;        ProceedingJoinPoint pjp = lazyGetProceedingJoinPoint(pmi);        JoinPointMatch jpm = getJoinPointMatch(pmi);        return invokeAdviceMethod(pjp, jpm, null, null);    }    ...}
public class MethodBeforeAdviceInterceptor implements MethodInterceptor, Serializable { // 由MethodBeforeAdviceAdapter创建    private MethodBeforeAdvice advice;    ...    @Override    public Object invoke(MethodInvocation mi) throws Throwable {        this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis() );        return mi.proceed();    }}
public class AspectJAfterAdvice extends AbstractAspectJAdvice implements MethodInterceptor, AfterAdvice, Serializable {    ...    @Override    public Object invoke(MethodInvocation mi) throws Throwable {        try {            return mi.proceed();        }        finally {            invokeAdviceMethod(getJoinPointMatch(), null, null);        }    }    ...}
public class AfterReturningAdviceInterceptor implements MethodInterceptor, AfterAdvice, Serializable { // 由AfterReturningAdviceAdapter创建    private final AfterReturningAdvice advice;    ...    @Override    public Object invoke(MethodInvocation mi) throws Throwable {        Object retVal = mi.proceed();        this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());        return retVal;    }}
public class AspectJAfterThrowingAdvice extends AbstractAspectJAdvice implements MethodInterceptor, AfterAdvice, Serializable {    ...    @Override    public Object invoke(MethodInvocation mi) throws Throwable {        try {            return mi.proceed();        }        catch (Throwable ex) {            if (shouldInvokeOnThrowing(ex)) {                invokeAdviceMethod(getJoinPointMatch(), null, ex);            }            throw ex;        }    }    ...}

 --> 拦截器接口

public interface MethodInterceptor extends Interceptor {    Object invoke(MethodInvocation invocation) throws Throwable;}
public interface Interceptor extends Advice {}
public interface Advice { // 通知}

 

转载于:https://www.cnblogs.com/bjorney/p/10430498.html

你可能感兴趣的文章
easyshell 安装
查看>>
UITextView 点击添加文字 光标处于最后方
查看>>
kudu 1.8.0(开发版) 源码安装
查看>>
LVS+Keepalived实现MySQL从库读操作负载均衡
查看>>
【转载】说说标准服务器架构(WWW+Image/CSS/JS+File+DB)续测试环境搭建
查看>>
day13-类的重写和类的私有方法
查看>>
[LeetCode][Java] Unique Paths II
查看>>
哈理工2015 暑假训练赛 zoj 2976 Light Bulbs
查看>>
Notes for C++
查看>>
web前端职业规划(转)
查看>>
用户体验 的一个原则,
查看>>
常用面试sql语句
查看>>
Kafka - 消费接口分析
查看>>
<s:property value=""/> 获取属性时的各种方式
查看>>
RF-RequestsLibrary
查看>>
【HDOJ】1892 See you~
查看>>
同伦延拓法中的几个数学常识
查看>>
毕业论文如何排版
查看>>
JS3 -- 模块(cmd amd)
查看>>
转:机器学习算法笔记:谱聚类方法
查看>>