AOP流程分析
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流程分析的更多相关文章
- SpringBoot启动流程分析(六):IoC容器依赖注入
SpringBoot系列文章简介 SpringBoot源码阅读辅助篇: Spring IoC容器与应用上下文的设计与实现 SpringBoot启动流程源码分析: SpringBoot启动流程分析(一) ...
- springboot 事务执行全流程分析
springboot 事务执行全流程分析 目录 springboot 事务执行全流程分析 1. 事务方法执行前的准备工作 2. 业务代码的调用 3. 事务方法执行后处理 4. 业务代码在事务和非事务中 ...
- 8、Struts2 运行流程分析
1.流程分析: 请求发送给 StrutsPrepareAndExecuteFilter StrutsPrepareAndExecuteFilter 询问 ActionMapper: 该请求是否是一个 ...
- freeswitch呼叫流程分析
今天翻文档时发现之前整理的关于freeswitch呼叫相关的内容,写成博文分享出来也方便我以后查阅. 整体结构图 FreeswitchCore 模块加载过程 freeswitch主程序初始化时会从mo ...
- u-boot 流程分析
u-boot 介绍: 对于计算机来说 , 从一开始上机通电是无法直接启动操作系统的 , 这中间需要一个引导过程 , 嵌入式Linux系统同样离不开引导程序 , 这个启动程序就叫启动加载程序(Boot ...
- thttpd和cgilua安装与运行流程分析
安装 参考如下博文安装thttpd软件 http://blog.csdn.net/21aspnet/article/details/7045845 http://blog.csdn.net/drago ...
- 【转】Hostapd工作流程分析
[转]Hostapd工作流程分析 转自:http://blog.chinaunix.net/uid-30081165-id-5290531.html Hostapd是一个运行在用户态的守护进程,可以通 ...
- u-boot中nandflash初始化流程分析(转)
u-boot中nandflash初始化流程分析(转) 原文地址http://zhuairlunjj.blog.163.com/blog/static/80050945201092011249136/ ...
- Android7.0 Phone应用源码分析(二) phone来电流程分析
接上篇博文:Android7.0 Phone应用源码分析(一) phone拨号流程分析 今天我们再来分析下Android7.0 的phone的来电流程 1.1TelephonyFramework 当有 ...
随机推荐
- F - Debate CodeForces - 1070F 思维
题目链接:https://vjudge.net/problem/CodeForces-1070F 具体思路:首先把所有的00放进去,然后对于10 和01 的取两个数目最小值t,排完序后将前t个加起来, ...
- CRF++模板使用(转)
CRF++模板构建分为两类,一类是Unigram标注,一类是Bigram标注. Unigram和Bigram模板分别生成CRF的状态特征函数 和转移特征函数 .其中 是标签, 是观测序列, ...
- java程序out of memory【转】
相信大家都有感触,线上服务内存OOM的问题,是最难定位的问题,不过归根结底,最常见的原因: 本身资源不够 申请的太多 资源耗尽 58到家架构部,运维部,58速运技术部联合进行了一次线上服务内存OOM问 ...
- 作为一个新手的Oracle(DBA)学习笔记【转】
一.Oracle的使用 1).启动 *DQL:数据查询语言 *DML:数据操作语言 *DDL:数据定义语言 DCL:数据控制语言 TPL:事务处理语言 CCL:指针控制语言 1.登录 Win+R—cm ...
- 一个python爬虫工具类
写了一个爬虫工具类. # -*- coding: utf-8 -*- # @Time : 2018/8/7 16:29 # @Author : cxa # @File : utils.py # @So ...
- Python实现好友全头像的拼接
微信好友全头像 话不多说,直接上代码 import itchat import math import PIL.Image as Image import os itchat.auto_login() ...
- nginx报502修复日志
参考:https://www.baidu.com/link?url=PGd7mgvalnQp0MOVZTyDJIvr6_eJn1hmPlmsLpdj2vH6w3FzMt3pZEd_MKpoiqX1OF ...
- [ python ] 集合的使用
集合的使用 可变数据类型,他里面的元素必须是不可变的数据类型,无序,不重复. 集合的增删查 集合是没有改这种说法的: (1)集合的元素无序的: (2)集合的元素为不可变类型 增加 add 为集 ...
- PCA算法和SVD
如果矩阵对某一个向量或某些向量只发生伸缩变换,不对这些向量产生旋转的效果,那么这些向量就称为这个矩阵的特征向量,伸缩的比例就是特征值.这里可以将特征值为负,特征向量旋转180度,也可看成方向不变,伸缩 ...
- window7 开启自带 ftp
添加 ftp 用户 在windows里添加一个用户.这个其实是你ftp的用户.当然你可以使用匿名访问,但是这样不怎么安全,要知道ftp外网其实也是可以连进来的.去把密码设一下,标准用户就可以了,不用管 ...