@Transactional 是Spring用于声明式事务的一个注解,实现基于AOP
关于AOP(Aspect Oriented Programming),这里摘取一下Spring官网的介绍
Aspect-oriented Programming (AOP) complements Object-oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns (such as transaction management) that cut across multiple types and objects. (Such concerns are often termed "crosscutting" concerns in AOP literature.)
通俗的理解是: 我预约了一家餐厅去一家餐厅用餐,在我进门之后,首先服务员要验证我的预约信息,接着要引领我到对应的座位。点菜之后用餐,用餐完成后,结账,反馈等等,我的核心是用餐,至于验证,引领等操作是围绕着我用餐而展开的。相当于对于我用餐本身的行为的补充。
AOP实现事务管理则是有以下流程: 在方法初始化时对于使用了@Transactional的类/方法生成了代理对象 调用时(必须通过代理对象调用,这里若不通过代理对象调用,则事务不生效)开始执行之前开启了事务,设置事务自动提交为false,待执行完成后提交,若异常则回滚。