Transactional是spring中定义的事务注解,在方法或类上加该注解开启事务。主要是通过反射获取bean的注解信息,利用AOP对编程式事务进行封装实现。AOP对事务的封装可以看我的这篇文章的介绍

我们先写个demo,感受它的加载过程。

spring事务注解:

1. 自定义一个注解

  1. /**
  2. * @Target 作用域(作用在方法上,类上,或是属性上)
  3. * @Retention 运行周期
  4. * @interface 定义注解
  5. */
  6. @Target(value = ElementType.METHOD)
  7. @Retention(RetentionPolicy.RUNTIME)
  8. public @interface MyAnnotation {
  9. //自定义注解的属性
  10. int id() default 0;
  11. String name() default "默认名称";
  12. String[]arrays();
  13. String title() default "默认标题";
  14. }

2. 测试

  1. import java.lang.reflect.Method;
  2. public class User {
  3.  
  4. @MyAnnotation(name="吴磊",arrays = {"2","3"})
  5. public void aMethod () {}
  6.  
  7. public void bMethod () {}
  8.  
  9. public static void main(String[] args) throws ClassNotFoundException {
  10. //1. 反射获取到类信息
  11. Class<?> forName = Class.forName("com.demo.User");
  12. //2. 获取到当前类(不包含继承)所有的方法
  13. Method[] declaredMethods = forName.getDeclaredMethods();
  14. //3. 遍历每个方法的信息
  15. for (Method method : declaredMethods) {
  16. System.out.println("方法名称:" + method.getName());
  17. //4. 获取方法上面的注解
  18. MyAnnotation annotation = method.getDeclaredAnnotation(MyAnnotation.class);
  19. if(annotation == null) {
  20. System.out.println("该方法上没有加注解....");
  21. }else {
  22. System.out.println("Id:" + annotation.id());
  23. System.out.println("Name:" + annotation.name());
  24. System.out.println("Arrays:" + annotation.arrays());
  25. System.out.println("Title:" + annotation.title());
  26. }
  27. System.out.println("--------------------------");
  28. }
  29. }
  30. }
  31.  
  32. =============================
  33. 【控制台输出】
  34. 方法名称:main
  35. 该方法上没有加注解....
  36. --------------------------
  37. 方法名称:aMethod
  38. Id:0
  39. Name:吴磊
  40. Arrays:[Ljava.lang.String;@74a14482
  41. Title:默认标题
  42. --------------------------
  43. 方法名称:bMethod
  44. 该方法上没有加注解....
  45. --------------------------

总结:通过上面这么一个小demo我们就能发现,反射获取到每一个方法的注解信息然后进行判断,如果这是@Transactional注解,spring就会开启事务。接下来我们可以按照这种思路基于上一篇博客的编程式事务自己实现一个事务注解。

手写注解事务:

1. 导包

  1. <dependencies>
  2. <!-- 引入Spring-AOP等相关Jar -->
  3. <dependency>
  4. <groupId>org.springframework</groupId>
  5. <artifactId>spring-core</artifactId>
  6. <version>3.0.6.RELEASE</version>
  7. </dependency>
  8. <dependency>
  9. <groupId>org.springframework</groupId>
  10. <artifactId>spring-context</artifactId>
  11. <version>3.0.6.RELEASE</version>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.springframework</groupId>
  15. <artifactId>spring-aop</artifactId>
  16. <version>3.0.6.RELEASE</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework</groupId>
  20. <artifactId>spring-orm</artifactId>
  21. <version>3.0.6.RELEASE</version>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.aspectj</groupId>
  25. <artifactId>aspectjrt</artifactId>
  26. <version>1.6.1</version>
  27. </dependency>
  28. <dependency>
  29. <groupId>aspectj</groupId>
  30. <artifactId>aspectjweaver</artifactId>
  31. <version>1.5.3</version>
  32. </dependency>
  33. <dependency>
  34. <groupId>cglib</groupId>
  35. <artifactId>cglib</artifactId>
  36. <version>2.1_2</version>
  37. </dependency>
  38.  
  39. <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
  40. <dependency>
  41. <groupId>com.mchange</groupId>
  42. <artifactId>c3p0</artifactId>
  43. <version>0.9.5.2</version>
  44. </dependency>
  45. <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
  46. <dependency>
  47. <groupId>mysql</groupId>
  48. <artifactId>mysql-connector-java</artifactId>
  49. <version>5.1.37</version>
  50. </dependency>
  51. </dependencies>

2. 配置spring.xml文件

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  3. xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/context
  8. http://www.springframework.org/schema/context/spring-context.xsd
  9. http://www.springframework.org/schema/aop
  10. http://www.springframework.org/schema/aop/spring-aop.xsd
  11. http://www.springframework.org/schema/tx
  12. http://www.springframework.org/schema/tx/spring-tx.xsd">
  13.  
  14. <!-- 扫描指定路劲 -->
  15. <context:component-scan base-package="com.wulei"/>
  16. <!-- 开启切面代理 -->
  17. <aop:aspectj-autoproxy />
  18. <!-- 1. 数据源对象: C3P0连接池 -->
  19. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  20. <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
  21. <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
  22. <property name="user" value="root"></property>
  23. <property name="password" value="root"></property>
  24. </bean>
  25.  
  26. <!-- 2. JdbcTemplate工具类实例 -->
  27. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  28. <property name="dataSource" ref="dataSource"></property>
  29. </bean>
  30.  
  31. <!-- 3. 配置事务 -->
  32. <bean id="dataSourceTransactionManager"
  33. class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  34. <property name="dataSource" ref="dataSource"></property>
  35. </bean>
  36.  
  37. </beans>

3.1 自定义事务注解 (通过反射解析方法上的注解,如果有这个注解就执行事务逻辑)

  1. import java.lang.annotation.ElementType;
  2. import java.lang.annotation.Retention;
  3. import java.lang.annotation.RetentionPolicy;
  4. import java.lang.annotation.Target;
  5. //@Transaction可以作用在类和方法上, 我们这里只作用在方法上。
  6. @Target(value = ElementType.METHOD)
  7. @Retention(RetentionPolicy.RUNTIME)
  8. /**
  9. * 自定义事务注解
  10. */
  11. public @interface MyAnnotation {
  12.  
  13. }

3.2 封装编程式事务

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.context.annotation.Scope;
  3. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  4. import org.springframework.stereotype.Component;
  5. import org.springframework.transaction.TransactionStatus;
  6. import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
  7. @Component
  8. @Scope("prototype") // 申明为多例,解决线程安全问题。
  9. /**
  10. * 手写编程式事务
  11. */
  12. public class TransactionUtil {
  13.  
  14. // 全局接受事务状态
  15. private TransactionStatus transactionStatus;
  16. // 获取事务源
  17. @Autowired
  18. private DataSourceTransactionManager dataSourceTransactionManager;
  19.  
  20. // 开启事务
  21. public TransactionStatus begin() {
  22. System.out.println("开启事务");
  23. transactionStatus = dataSourceTransactionManager.getTransaction(new DefaultTransactionAttribute());
  24. return transactionStatus;
  25. }
  26.  
  27. // 提交事务
  28. public void commit(TransactionStatus transaction) {
  29. System.out.println("提交事务");
  30. if(dataSourceTransactionManager != null) dataSourceTransactionManager.commit(transaction);
  31. }
  32.  
  33. // 回滚事务
  34. public void rollback(TransactionStatus transaction) {
  35. System.out.println("回滚事务...");
  36. if(dataSourceTransactionManager != null) dataSourceTransactionManager.rollback(transaction);
  37. }
  38. }

3.3 通过AOP封装事务工具类, 基于环绕通知和异常通知来触发事务。

  1. import java.lang.reflect.Method;
  2. import org.aspectj.lang.ProceedingJoinPoint;
  3. import org.aspectj.lang.annotation.AfterThrowing;
  4. import org.aspectj.lang.annotation.Around;
  5. import org.aspectj.lang.annotation.Aspect;
  6. import org.aspectj.lang.reflect.MethodSignature;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Component;
  9. import org.springframework.transaction.TransactionStatus;
  10. import org.springframework.transaction.interceptor.TransactionAspectSupport;
  11. import com.wulei.transaction.TransactionUtil;
  12. @Aspect// 申明为切面
  13. @Component
  14. /**
  15. * 切面类封装事务逻辑
  16. */
  17. public class AopTransaction {
  18.  
  19. @Autowired
  20. private TransactionUtil transactionUtil;
  21.  
  22. private TransactionStatus transactionStatus;
  23. /**
  24. * 环绕通知 在方法之前和之后处理事情
  25. * @param pjp 切入点
  26. */
  27. @Around("execution(* com.wulei.service.*.*(..))")
  28. public void around(ProceedingJoinPoint pjp) throws Throwable {
  29. // 1.获取方法的注解
  30. MyAnnotation annotation = this.getMethodMyAnnotation(pjp);
  31. // 2.判断是否需要开启事务
  32. transactionStatus = begin(annotation);
  33. // 3.调用目标代理对象方法
  34. pjp.proceed();
  35. // 4.判断关闭事务
  36. commit(transactionStatus);
  37. }
  38. /**
  39. * 获取代理方法上的事务注解
  40. * @param pjp 切入点
  41. */
  42. private MyAnnotation getMethodMyAnnotation(ProceedingJoinPoint pjp) throws Exception {
  43. //1. 获取代理对对象的方法
  44. String methodName = pjp.getSignature().getName();
  45. //2. 获取目标对象
  46. Class<?> classTarget = pjp.getTarget().getClass();
  47. //3. 获取目标对象类型
  48. Class<?>[] par = ((MethodSignature) pjp.getSignature()).getParameterTypes();
  49. //4. 获取目标对象方法
  50. Method objMethod = classTarget.getMethod(methodName, par);
  51. //5. 获取该方法上的事务注解
  52. MyAnnotation annotation = objMethod.getDeclaredAnnotation(MyAnnotation.class);
  53. return annotation;
  54. }
  55. /** 开启事务 */
  56. private TransactionStatus begin(MyAnnotation annotation) {
  57. if(annotation == null) return null;
  58. return transactionUtil.begin();
  59. }
  60. /** 关闭事务 */
  61. private void commit(TransactionStatus transactionStatus) {
  62. if(transactionStatus != null) transactionUtil.commit(transactionStatus);
  63. }
  64. /**
  65. * 异常通知进行 回滚事务
  66. */
  67. @AfterThrowing("execution(* com.wulei.service.*.*(..))")
  68. public void afterThrowing() {
  69. // 获取当前事务 直接回滚
  70. //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
  71. if(transactionStatus != null) transactionUtil.rollback(transactionStatus);
  72. }
  73. }

4. 编写dao层

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.jdbc.core.JdbcTemplate;
  3. import org.springframework.stereotype.Repository;
  4. /*
  5. CREATE TABLE `t_users` (
  6. `name` varchar(20) NOT NULL,
  7. `age` int(5) DEFAULT NULL,
  8. PRIMARY KEY (`name`)
  9. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  10. */
  11. @Repository
  12. public class UserDao {
  13. @Autowired
  14. private JdbcTemplate jdbcTemplate;
  15.  
  16. public int add(String name, Integer age) {
  17. String sql = "INSERT INTO t_users(NAME, age) VALUES(?,?);";
  18. int result = jdbcTemplate.update(sql, name, age);
  19. System.out.println("插入成功");
  20. return result;
  21. }
  22. }

5. 编写service

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.stereotype.Service;
  3. import com.wulei.dao.UserDao;
  4. import com.wulei.transaction.MyAnnotation;
  5. @Service
  6. public class UserService {
  7.  
  8. @Autowired
  9. private UserDao userDao;
  10.  
  11. // 加上事务注解
  12. @MyAnnotation
  13. public void add() {
  14. userDao.add("test001", 20);
  15. int i = 1 / 0;
  16. userDao.add("test002", 21);
  17. // // 如果非要try,那么出现异常不会被aop的异常通知监测到,必须手动在catch里面回滚事务。
  18. // try {
  19. // userDao.add("test001", 20);
  20. // int i = 1 / 0;
  21. // userDao.add("test002", 21);
  22. // } catch (Exception e) {
  23. // // 回滚当前事务
  24. // System.out.println("回滚");
  25. // TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
  26. // }
  27. }
  28.  
  29. public void del() {
  30. System.out.println("del...");
  31. }
  32. }

6. 测试

  1. import org.springframework.context.support.ClassPathXmlApplicationContext;
  2. import com.wulei.service.UserService;
  3. public class Main {
  4.  
  5. public static void main(String[] args) {
  6. ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
  7. UserService userService = (UserService) applicationContext.getBean("userService");
  8. // aop()对userService类进行了拦截,添加自定义事务注解的方法会触发事务逻辑
  9. userService.add();
  10. // del()方法没有加注解,则什么也不会触发。
  11. //userService.del();
  12. }
  13. }

@Transactional实现原理的更多相关文章

  1. Java:Spring @Transactional工作原理

    本文将深入研究Spring的事务管理.主要介绍@Transactional在底层是如何工作的.之后的文章将介绍: propagation(事务传播)和isolation(隔离性)等属性的使用 事务使用 ...

  2. 25.Spring @Transactional工作原理

    转自:http://www.importnew.com/12300.html 本文将深入研究Spring的事务管理.主要介绍@Transactional在底层是如何工作的.之后的文章将介绍: prop ...

  3. 事务之五:Spring @Transactional工作原理

    本文将深入研究Spring的事务管理.主要介绍@Transactional在底层是如何工作的. JPA(Java Persistence API--java持久层)和事务管理 很重要的一点是JPA本身 ...

  4. JPA数据懒加载LAZY配合事务@Transactional使用(三)

    上篇博文<JPA数据懒加载LAZY和实时加载EAGER(二)>讲到,如果使用懒加载来调用关联数据,必须要保证主查询session(数据库连接会话)的生命周期没有结束,否则,你是无法抽取到数 ...

  5. 通俗的讲法理解spring的事务实现原理

    拿房屋买卖举例,流程:销售房屋 -- 接待员 -- 销售员 -- 财务 售楼处 存放着所有待售和已售的房屋数据(数据源 datasource) 总经理 带领一套自己的班底,下属员工都听自己的,服务于售 ...

  6. Spring 事务注解@Transactional

    事务管理一般有编程式和声明式两种,编程式是直接在代码中进行编写事物处理过程,而声名式则是通过注解方式或者是在xml文件中进行配置,相对编程式很方便. 而注解方式通过@Transactional 是常见 ...

  7. 玩转Spring--消失的事务@Transactional

    消失的事务 端午节前,组内在讨论一个问题: 一个没有加@Transactional注解的方法,去调用一个加了@Transactional的方法,会不会产生事务? 文字苍白,还是用代码说话. 先写一个@ ...

  8. @Transactional(转)

    概述@Transactional 是声明式事务管理 编程中使用的注解 添加位置 接口实现类或接口实现方法上,而不是接口类中访问权限:public 的方法才起作用 @Transactional 注解应该 ...

  9. @Transactional(事务讲解)和springboot 整合事务

    概述 事务在编程中分为两种:声明式事务处理和编程式事务处理 编程式事务处理:编码方式实现事务管理,常与模版类TransactionTemplate(推荐使用) 在业务代码中实现事务. 可知编程式事务每 ...

随机推荐

  1. window.location.hash(hash应用)---跳转到hash值制定的具体页面

    location是javascript里边管理地址栏的内置对象,比如location.href就管理页面的url,用location.href=url就可以直接将页面重定向url.而location. ...

  2. 模板_LCA

    // luogu-judger-enable-o2 #include<bits/stdc++.h> #define maxn 1000002 //#define int long long ...

  3. 2019 南京网络赛A

    南京网络赛自闭现场 https://nanti.jisuanke.com/t/41298 二维偏序经典题型 二维前缀和!!! #include<bits/stdc++.h> using n ...

  4. 同一个tomcat部署多个项目

    在开发项目中,有时候我们需要在同一个tomcat中部署多个项目,小编之前也是遇到了这样的情况,碰过不少的壁,故整理总结如下,以供大家参考.(以Linux为例,其他系统同样适用) 一.首先将需要部署的项 ...

  5. sock( ) bind( ) connect( )

    Linux下的socket()函数 调用头文件<sys/socket.h>中的socket函数 int socket(int af, int type, int protocol); 1) ...

  6. memcached空指针内存错误与死循环问题分析(memcached dead loop and crash bug! issue #260 and issue #370)

    (由于这是发在memcached邮件列表的,所以只能用一下蹩脚的英文了) (you should read the discuss about issue #260 first:  https://g ...

  7. MAC截图工具

    截图快捷键 ctrl+shift+A

  8. Vue知识整理12:事件绑定

    采用v-on命令进行事件的绑定操作,通过单击按钮,实现按钮文字上数值的增加 带参数的事件过程 可以添加$event事件,实现事件信息的获取

  9. gzip, deflate delphi xe 2 解码 成功 哈哈

    2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 http://bbs.csdn.net/topics/190020986   ...

  10. nohup后台运行

    1.信息输出 nohup java -jar xxxx.jar & 2.信息不输出 nohup java -jar xxxx.jar >/dev/null 2>&1 &am ...