Spring Aop与声明式事务
1.对某实现BeanDefinition的对象,先实例化,后经过属性填充。
2.DefaultListableBeanFactory对象的initializeBean(...)方法中。
3.调用实现BeanPostProcessor接口的AnnotationAwareAspectJAutoProxyCreator类对象的postProcessAfterInitialization(...)
public class AnnotationAwareAspectJAutoProxyCreator {//解决代理对象的循环依赖//将其放入三级缓冲中,对某对象进行赋值操作后调用getEarlyBeanReference()//方法将代理对象提前暴露处理,等到该实例对象通过AnnotationAwareAspectJAutoProxyCreator类 //创建代理时,发现earlyProxyReferences存在对象名称,就直接返回代理对象 private final Set<Object> earlyProxyReferences;//存放代理对象的字节码private final Map<Object, Class<?>> proxyTypes;//存放可以被代理的对象private final Map<Object, Boolean> advisedBeans;//通过实例化对象创建代理对象public Object postProcessAfterInitialization() {if (bean != null) {Object cacheKey = this.getCacheKey(bean.getClass(), beanName);//如果之前没有创建过该实例化对象,则调用wrapIfNecessary()方法创建//代理对象if (!this.earlyProxyReferences.contains(cacheKey)) {return this.wrapIfNecessary(bean, beanName, cacheKey)->{//得到实例化bean的advices和AdvisorObject[] specificInterceptors = this.getAdvicesAndAdvisorsForBean(..);// specificInterceptors大于0,则创建代理对象,执行下面的语句//存放可以能被代理的对象this.advisedBeans.put(cacheKey, Boolean.TRUE);//创建代理对象, 通过advisor|.class|beanName|被填充属性的实例化对象Object proxy = this.createProxy(specificInterceptors,...);};//存放代理对象的字节码this.proxyTypes.put(cacheKey, proxy.getClass());return proxy;}}}return bean;} }
4.在创建createProxy(specificInterceptors,...)方法中
//创建proxyFactory,其属性// aopProxyFactory= new DefaultAopProxyFactory(); 根据该类创建代理对象。// targetSource 存放对象的实例(为属性赋值);// advisorChainFactory = new DefaultAdvisorChainFactory();// advisors 初始化Advisor// interfaces 接口数组// 1.@Aspect// Advisor的实现类InstantiationModelAwarePointcutAdvisorImpl// 其属性有pointcut,instantiatedAdvice有AspectJAfterThrowingAdvice// AspectJAfterReturningAdvice,AspectJAfterAdvice,AspectJAroundAdvice// AspectJMethodBeforeAdvice// Advisor的实现类ExposeInvocationInterceptor // 其属性advice ExposeInvocationInterceptor // 2.@Transactional // Advisor的实现类BeanFactoryTransactionAttributeSourceAdvisor// 其属性pointcut, advice =TransactionInterceptor ,beanFactory Object createProxy(specificInterceptors,...){ProxyFactory proxyFactory = new ProxyFactory();// 初始化proxyFactory对象return proxyFactory.getProxy(this.getProxyClassLoader())->{return this.createAopProxy().getProxy(classLoader)->{// DefaultAopProxyFactory对象.createAopProxy(this)return this.getAopProxyFactory().createAopProxy(this).getProxy(classLoader)-> {// 创建jdk动态代理,config为ProxyFactory对象// 代理对象名字$Proxy23// 接口InvocationHandler.invoke(...)的实现类// JdkDynamicAopProxy类return new JdkDynamicAopProxy(config).getProxy(classLoader);// 创建cglib代理// 属性advised=ProxyFactoryreturn new ObjenesisCglibAopProxy(config).getProxy(classLoader)->{// 获取目标类Class<?> rootClass = this.advised.getTargetClass();Enhancer enhancer = this.createEnhancer();enhancer.setClassLoader(classLoader);enhancer.setSuperclass(rootClass);enhancer.setInterfaces(...)//SpringProxy|Advised// 7个回调。callbacks[0]=CglibAopProxy$DynamicAdvisedInterceptor// 其实现接口MethodInterceptor.intercept(...) Callback[] callbacks = this.getCallbacks(rootClass);enhancer.setCallbackFilter(...);enhancer.setCallbackTypes(types);return this.createProxyClassAndInstance(enhancer, callbacks)->{//生成 类名$$EnhancerBySpringCGLIB$$8b69cafcClass<?> proxyClass = enhancer.createClass();Constructor<?> ctor = proxyClass.getDeclaredConstructor();proxyInstance= ctor.newInstance(this.constructorArgs);return ((Factory)proxyInstance).setCallbacks(callbacks);};};}}};
} // 接口AopProxy.Object getProxy(@Nullable ClassLoader var1)
// 实现类JdkDynamicAopProxy且该类继承接口InvocationHandler.invoke(...)方法
// 实现类ObjenesisCglibAopProxy且该类继承CglibAopProxy
5.在执行方法时(Aspect拦截的方法),被CglibAopProxy$DynamicAdvisedInterceptor类的实例对象的intercept(...)方法拦截。
// CglibAopProxy$DynamicAdvisedInterceptor类的实例对象属性为
// advised=ProxyFactory的实例对象
// proxy为代理对象,method 拦截的方法,args参数,methodProxy为CreateInfo.C1|C2
// C1类字节码,C2为代理类字节码
// intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy)// advice
// ExposeInvocationInterceptor
// AspectJAfterThrowingAdvice
// AfterReturningAdviceInterceptor其属性advice=AspectJAfterReturningAdvice
// AspectJAfterAdvice
// AspectJAroundAdvice
// MethodBeforeAdviceInterceptor其属性advice=AspectJMethodBeforeAdvice// 如果是@Transactional,则返回一个值chains=
// TransactionInterceptor 其属性beanFactory,
// 其属性transactionAttributeSource对应的类AnnotationTransactionAttributeSource
List<Object> chains = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);//new CglibMethodInvocation对象,并调用其父类ReflectiveMethodInvocation的
// proceed()方法作用currentInterceptorIndex加1,直到执行调用完
// interceptorsAndDynamicMethodMatchers中的advice。
//
// 该对象属性 interceptorsAndDynamicMethodMatchers 存放chains中的advice
// currentInterceptorIndex = -1 初始-1,处理完一个advice,该值加1。
new CglibAopProxy.CglibMethodInvocation(...).proceed()->{//调用chains数组中对象的invoke(mi); //mi为CglibAopProxy.CglibMethodInvocation对象// 第一个advice:ExposeInvocationInterceptor 属性ThreadLocal<MethodInvocation> // invocation,目的将mi放到ThreadLocal中,通过ExposeInvocationInterceptor// .invocation.get()ExposeInvocationInterceptor对象invoke(mi); // ProceedingJoinPoint joinPoint为MethodInvocationProceedingJoinPoint对象// 其属性methodInvocation=为CglibAopProxy.CglibMethodInvocation对象// 其属性signature=为拦截的方法对象try {try {// // 环绕方法执行joinPoint.proceed(); 实际就是将其属性// 的mi对象重新克隆出一个新的对象执行,currentInterceptorIndex加1AspectJAroundAdvice.invokeAdviceMethod(...)->{//这段代码时使用@Around下的方法的执行逻辑try {1.执行joinPoint.proceed()前的逻辑 2.joinPoint.proceed()->{AspectJMethodBeforeAdvice.invokeAdviceMethod(...);//拦截的方法体执行this.invokeJoinpoint(); 3.执行joinPoint.proceed()后的逻辑}catch(Exception e)4.执行异常逻辑}finally{5.执行最终逻辑} }; } finally {AspectJAfterAdvice.invokeAdviceMethod(...);}AspectJAfterReturningAdvice.afterReturning(...);}catch (Throwable var3) { AspectJAfterThrowingAdvice.invokeAdviceMethod(...);throw var3;}
};public class AspectJAfterThrowingAdvice {public Object invoke(MethodInvocation mi) throws Throwable {try {return mi.proceed();} catch (Throwable var3) {if (this.shouldInvokeOnThrowing(var3)) {this.invokeAdviceMethod(this.getJoinPointMatch(), (Object)null, var3);}throw var3;}}
}
public class AfterReturningAdviceInterceptor {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 AspectJAfterAdvice {public Object invoke(MethodInvocation mi) throws Throwable {Object var2;try {var2 = mi.proceed();} finally {this.invokeAdviceMethod(this.getJoinPointMatch(), (Object)null, (Throwable)null);}return var2;}
}public class AspectJAroundAdvice {public Object invoke(MethodInvocation mi) throws Throwable {if (!(mi instanceof ProxyMethodInvocation)) {throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi);} else {ProxyMethodInvocation pmi = (ProxyMethodInvocation)mi;ProceedingJoinPoint pjp = this.lazyGetProceedingJoinPoint(pmi);JoinPointMatch jpm = this.getJoinPointMatch(pmi);return this.invokeAdviceMethod(pjp, jpm, (Object)null, (Throwable)null);}}
}public class MethodBeforeAdviceInterceptor {public Object invoke(MethodInvocation mi) throws Throwable {this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());return mi.proceed();}
}
6.在执行方法时(@Transactional方法),被CglibAopProxy$DynamicAdvisedInterceptor类的实例对象的intercept(...)方法拦截。
//new CglibAopProxy.CglibMethodInvocation(...).proceed()
// 遍历执行interceptorsAndDynamicMethodMatchers
public class TransactionInterceptor {public Object invoke(MethodInvocation invocation)->{//其父类TransactionAspectSupport的方法this.invokeWithinTransaction()->{//DataSourceTransactionManager对象.doBegin() //con.setAutoCommit(false);TransactionAspectSupport.TransactionInfo txInfo = this.createTransactionIfNecessary(tm, txAttr, joinpointIdentification);result = null;try {//执行方法体result = invocation.proceedWithInvocation();} catch (Throwable var17) {//回滚this.completeTransactionAfterThrowing(txInfo, var17);throw var17;} finally {//清除ThreadLocal<TransactionAspectSupport.TransactionInfo> // transactionInfoHolderthis.cleanupTransactionInfo(txInfo);}//提交事务this.commitTransactionAfterReturning(txInfo);return result;}}
}
// 主要接口方法 Pointcut getPointcut()/getAdvice()
public class BeanFactoryTransactionAttributeSourceAdvisor {// 值为AnnotationTransactionAttributeSource对象private TransactionAttributeSource transactionAttributeSource;// 值为DefaultListableBeanFactoryprivate BeanFactory beanFactory;// 值TransactionInterceptor对象t// 如果该对象t中的 PlatformTransactionManager transactionManager为null,则从对象t的 // transactionManagerCache.get(DEFAULT_TRANSACTION_MANAGER_KEY)// 如果为null,则beanFactory中得到DataSourceTransactionManager对象,并放入// transactionManagerCache中key为DEFAULT_TRANSACTION_MANAGER_KEY// 用ProxyFactory对象的方法getInterceptorsAndDynamicInterceptionAdvice(// method,targetClass)得到TransactionInterceptor对象// 使用TransactionInterceptor对象.invokeWithinTransaction(...)private transient volatile Advice advice;}//spring事务注解属性资源
public class AnnotationTransactionAttributeSource{//解析公共方法private final boolean publicMethodsOnly = true;//值为SpringTransactionAnnotationParser//SpringTransactionAnnotationParser.parseTransactionAnnotation(AnnotatedElement ae)//方法: 解析类方法上的@Transaction的属性赋值给RuleBasedTransactionAttribute对象private final Set<TransactionAnnotationParser> annotationParsers;//储存带有@Transaction注解方法// key MethodClassKey类 // value DefaultTransactionAttribute=PROPAGATION_REQUIRED,ISOLATION_DEFAULT// RuleBasedTransactionAttributeprivate final Map<Object, TransactionAttribute> attributeCache;}public interface TransactionDefinition {int PROPAGATION_REQUIRED = 0;int PROPAGATION_SUPPORTS = 1;int PROPAGATION_MANDATORY = 2;int PROPAGATION_REQUIRES_NEW = 3;int PROPAGATION_NOT_SUPPORTED = 4;int PROPAGATION_NEVER = 5;int PROPAGATION_NESTED = 6;int ISOLATION_DEFAULT = -1;int ISOLATION_READ_UNCOMMITTED = 1;int ISOLATION_READ_COMMITTED = 2;int ISOLATION_REPEATABLE_READ = 4;int ISOLATION_SERIALIZABLE = 8;int TIMEOUT_DEFAULT = -1;
}TransactionAspectSupport.TransactionInfo 其属性
transactionManager=DataSourceTransactionManager对象
transactionAttribute=PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
joinpointIdentification=org.sang.security01.OrderService.setOrder某方法
transactionStatus=DefaultTransactionStatus对象
this$0=TransactionInterceptor对象
Spring Aop与声明式事务相关推荐
- Spring AOP实现声明式事务代码分析
众所周知,Spring的声明式事务是利用AOP手段实现的,所谓"深入一点,你会更快乐",本文试图给出相关代码分析. AOP联盟为增强定义了org.aopalliance.aop.A ...
- 实现自己的BeanFactory、AOP以及声明式事务
实现自己的BeanFactory 在使用spring时,我们很少用& ...
- Spring源码——声明式事务流程
前言 最近回顾了一下Spring源码,准备用思维导图的方式简单的将整个源码内容的流程展示出来,思维导图.图片等文件更新在https://github.com/MrSorrow/spring-frame ...
- spring 注解开启声明式事务
spring开启声明式事务: 导入依赖: pom.xml <dependencies><!-- https://mvnrepository.com/artifact/org.spri ...
- spring+mybatis之声明式事务管理初识(小实例)
前几篇的文章都只是初步学习spring和mybatis框架,所写的实例也都非常简单,所进行的数据访问控制也都很简单,没有加入事务管理.这篇文章将初步接触事务管理. 1.事务管理 理解事务管理之前,先通 ...
- spring——使用注解声明式事务整合jdbc——GRUD
准备阶段: pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns=&qu ...
- spring——使用xml声明式事务整合jdbc——GRUD
准备阶段: pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns=&qu ...
- Spring+mybatis整合声明式事务异常之org.springframework.transaction.TransactionTimedOutException: Transaction ..
1.异常信息 org.springframework.transaction.TransactionTimedOutException: Transaction timed out: deadline ...
- Spring如何用“声明式事务”保护亿万数据安全?【万字解决并发冲突】
Hello,你好呀,我是灰小猿,一个超会写bug的程序猿
- Spring配置文件详解三:Spring声明式事务管理
1.声明式事务管理 Spring提供了声明式事务管理,这是通过Spring AOP实现的. 原理:Spring中进行事务管理的通常方式是利用AOP(面向切片编程)的方式,为普通java类封装事务控制, ...
最新文章
- 一步一步SharePoint 2007之八:允许所有域用户访问网站
- 容量法和库仑法的异同点_【图文专辑】第十讲:容量法高锰酸盐指数的测定
- c语言检测文件bom,C语言关联TC中BOMWindow与BOPWindow
- 外卖平台降费,能否成为“全村人的希望”?
- 是个狠角色。。 | 今日最佳
- php怎么清空cookies,php cookie如何清除
- Oracle数据库中NOLOGGING和FORCE LOGGING
- 重磅!!Gradle 6.6 发布,大幅提升性能!
- 职业教育相关的核心期刊有哪些?
- Linux中锐捷认证开启WiFi热点解决方案
- Linux 创建oracle数据库
- vs code的php格式化
- html,js实现对联广告
- ENSP华为路由器FTP服务器实验
- 同济子豪兄github_【B站UP主-同济子豪兄】华为云ModelArts零代码开发病虫害识别应用...
- 数据库求候选码的算法
- MQ2烟雾传感器模块——stm32f103
- 转载-Android EventLog含义
- 方差、协方差、四分位差笔记
- 解决vue/es6语法低版本安卓手机显示白屏的兼容性问题
热门文章
- 如果高考顺利,此刻我已经在工地打灰了
- 富人和穷人的十三大经典差异!!!
- kafka消费者重复消费同一个topic
- 【Unity开发】扑克的转换
- 提高代码效率的20个javascript小窍门(2)
- Caffeine本地缓存学习
- 春夏换季,护肤先行,红玫瑰集团的美丽秘笈
- android 华为 打开相册,【报Bug】Android 9, 华为手机 使用plus.gallery.pick获取视频,打开相册之后,无法选中视频...
- 广东全国计算机报名系统官网,2019年广东计算机考试报名入口
- 企业电商升级转型的助推器