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<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
// 获取所有Advisor(Advice),排序如下:@Around -> @Before -> @After -> @AfterReturning -> @AfterThrowing -> @Around -> @Before -> ...
List<Advisor> candidateAdvisors = findCandidateAdvisors();
List<Advisor> 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<Advisor> findCandidateAdvisors() {
List<Advisor> advisors = super.findCandidateAdvisors();
advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
return advisors;
}
...
}

--> BeanFactoryAspectJAdvisorsBuilderAdapter.buildAspectJAdvisors

public class BeanFactoryAspectJAdvisorsBuilder {
...
private final AspectJAdvisorFactory advisorFactory; // ReflectiveAspectJAdvisorFactory
...
public List<Advisor> buildAspectJAdvisors() {
List<String> aspectNames = this.aspectBeanNames;
// 无缓存
if (aspectNames == null) {
synchronized (this) {
...
if (aspectNames == null) {
List<Advisor> advisors = new LinkedList<Advisor>();
...
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<Advisor> 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<Advisor> getAdvisors(MetadataAwareAspectInstanceFactory aspectInstanceFactory) {
Class<?> aspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
...
List<Advisor> advisors = new LinkedList<Advisor>();
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<Object> 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<Object> 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<Object> 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<Object> 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<AdvisorAdapter> adapters = new ArrayList<AdvisorAdapter>(3);

    public DefaultAdvisorAdapterRegistry() {
registerAdvisorAdapter(new MethodBeforeAdviceAdapter());
registerAdvisorAdapter(new AfterReturningAdviceAdapter());
registerAdvisorAdapter(new ThrowsAdviceAdapter());
} ... @Override
public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {
List<MethodInterceptor> interceptors = new ArrayList<MethodInterceptor>(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 { // 通知
}

AOP流程分析的更多相关文章

  1. SpringBoot启动流程分析(六):IoC容器依赖注入

    SpringBoot系列文章简介 SpringBoot源码阅读辅助篇: Spring IoC容器与应用上下文的设计与实现 SpringBoot启动流程源码分析: SpringBoot启动流程分析(一) ...

  2. springboot 事务执行全流程分析

    springboot 事务执行全流程分析 目录 springboot 事务执行全流程分析 1. 事务方法执行前的准备工作 2. 业务代码的调用 3. 事务方法执行后处理 4. 业务代码在事务和非事务中 ...

  3. 8、Struts2 运行流程分析

    1.流程分析: 请求发送给 StrutsPrepareAndExecuteFilter StrutsPrepareAndExecuteFilter 询问 ActionMapper: 该请求是否是一个 ...

  4. freeswitch呼叫流程分析

    今天翻文档时发现之前整理的关于freeswitch呼叫相关的内容,写成博文分享出来也方便我以后查阅. 整体结构图 FreeswitchCore 模块加载过程 freeswitch主程序初始化时会从mo ...

  5. u-boot 流程分析

    u-boot 介绍: 对于计算机来说 , 从一开始上机通电是无法直接启动操作系统的 , 这中间需要一个引导过程 , 嵌入式Linux系统同样离不开引导程序 ,  这个启动程序就叫启动加载程序(Boot ...

  6. thttpd和cgilua安装与运行流程分析

    安装 参考如下博文安装thttpd软件 http://blog.csdn.net/21aspnet/article/details/7045845 http://blog.csdn.net/drago ...

  7. 【转】Hostapd工作流程分析

    [转]Hostapd工作流程分析 转自:http://blog.chinaunix.net/uid-30081165-id-5290531.html Hostapd是一个运行在用户态的守护进程,可以通 ...

  8. u-boot中nandflash初始化流程分析(转)

    u-boot中nandflash初始化流程分析(转) 原文地址http://zhuairlunjj.blog.163.com/blog/static/80050945201092011249136/ ...

  9. Android7.0 Phone应用源码分析(二) phone来电流程分析

    接上篇博文:Android7.0 Phone应用源码分析(一) phone拨号流程分析 今天我们再来分析下Android7.0 的phone的来电流程 1.1TelephonyFramework 当有 ...

随机推荐

  1. 首次成功的web渗透

    web渗透 今天给大家讲一个最近做的一件令我振奋的一件事情 渗透培训刚刚结束的第二天 我在公网上挖到了我人生中的第一个站 总体来说个人真的很振奋人心      这个网站还没有进行更改但我已经通知了他们 ...

  2. windows环境下搭建Redis集群

    转载请注明出处,原文章地址: https://www.cnblogs.com/tommy-huang/p/6240083.html Redis集群: 如果部署到多台电脑,就跟普通的集群一样:因为Red ...

  3. maven的初步理解

    [情景] 在进行JAVA项目开发的过程中,代码写好后,需要经过编译.打包.运行.测试.部署等过程. 在JAVA项目的开发阶段,就会根据业务的需要引入许多jar包来实现功能,但我们需求的jar包本身可能 ...

  4. centos上git搭建

    1 git的安装需要一些包: yum install curl-devel expat-devel gettext-devel openssl-devel zlib-devel gcc perl-Ex ...

  5. 《跟老齐学Python Django实战》读后感

    1.说一下这本书,讲解的很细致,内容选取足够入门Django. 2.在学习这本书要注意的几点: <1>如果你想跟着敲这本书的代码必须要安装:Django版本1.10.1(当然也可以玩玩新版 ...

  6. C语言花括号

    由于C语言本身就是函数式语言,说白了,C程序就是由函数构成的! 所以花括号肯定是用在函数之中,包括函数中的各种流程控制语句中. 实际上,C程序中花括号{}的作用:就是把多个单条语句用花括号{}括起来组 ...

  7. Qt 下载列表地址

    每次下载Qt总是找好长时间,收藏一下地址 Qt 下载列表地址 https://www.qt.io/download-open-source/#section-9 教育网镜像下载 http://mirr ...

  8. ubuntu包管理命令apt和dpkg的用法

    apt-get命令: apt-get是debian,ubuntu发行版的包管理工具,与红帽中的yum工具非常类似,适用于deb包管理式的操作系统,主要用于自动从互联网的软件仓库中搜索.安装.升级.卸载 ...

  9. 【洛谷】P4585 [FJOI2015]火星商店问题

    题解 题目太丧,OJ太没有良心,我永远喜欢LOJ! (TLE报成RE,垃圾洛谷,我永远喜欢LOJ) 好的,平复一下我debug了一上午崩溃的心态= =,写一写这道题的题解 把所有限制去掉,给出一个值, ...

  10. MVC Partial页面的使用

    先建立Action: public PartialViewResult CurrentCount() { ViewBag.Count = CurrentUserCount; return Partia ...