PS:本人从事JavaWeb行业不足3年的理解,也是人生中的第一篇技术文章,简单说一下自己对于该注解的理解,不足处希望大佬们指点
想必大家对于@Transactional注解都不陌生,我们通常使用的时候不知道他在后面默默付出了些什么,接下来我们一起走进@Transactional
目录
1.@Transactional的作用
@Transactional 可以作用于接口、接口方法、类以及类方法上。当作用于类上时,该类的所有 public 方法将都具有该类型的事务属性,同时,我们也可以在方法级别使用该标注来覆盖类级别的定义。
2.@Transactional注解中的参数
我们戳进@Transactional里面会看到
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Transactional {
//可选的限定描述符,指定使用的事务管理器
String value() default "";
//可选的事务传播行为,具体看Propagation中定义的属性
Propagation propagation() default Propagation.REQUIRED;
//可选的事务隔离级别
Isolation isolation() default Isolation.DEFAULT;
//事务超时时间设置
int timeout() default TransactionDefinition.TIMEOUT_DEFAULT;
//读写或只读事务,默认读写
boolean readOnly() default false;
//导致事务回滚的异常类数组,
//注意项:即使自定义异常,也必须继承自Throwable
Class<? extends Throwable>[] rollbackFor() default {};
//导致事务回滚的异常类名字数组
//类名数组,必须继承自Throwable
String[] rollbackForClassName() default {};
//不会导致事务回滚的异常类数组
//Class对象数组,必须继承自Throwable
Class<? extends Throwable>[] noRollbackFor() default {};
//不会导致事务回滚的异常类名字数组
//类名数组,必须继承自Throwable
String[] noRollbackForClassName() default {};
}
顺带提一下事物的4个特性
1.原子性:对数据进行操作的时候,要么全都执行,要么全都不执行。
2.一致性:和原子性是分不开的,事务执行成功,说明全部都执行了,那么就使数据库从一个一致性状态变到另一个一致性状了。
3.隔离性: 一个事务的执行不能被其他事务干扰
4.持续性: 事务一旦提交成功,那么数据库里的数据就会永久性的改变。
事物特性参考源处:https://www.jianshu.com/p/bcfd48c4cbf4
3.@Transactional注解的实现
由上面看到的属性及注释我们进注解的实现源码看一下吧
3.1 @Transactional核心配置
在上图我们能看到这些,其中核心配置的是AnnotationTransactionAttributeSource(注解事物属性配置)这个类。我们能看到该类继承了抽象类AbstractFallbackTransactionAttributeSource,这个类实现 TransactionAttributeSource接口,重写了getTransactionAttribute方法,我们来看看这个方法实现了什么,附上官方源码及注释
/**
* Determine the transaction attribute for this method invocation.
* <p>Defaults to the class's transaction attribute if no method attribute is found.
* @param method the method for the current invocation (never {@code null})
* @param targetClass the target class for this invocation (may be {@code null})
* @return TransactionAttribute for this method, or {@code null} if the method
* is not transactional
*/
public TransactionAttribute getTransactionAttribute(Method method, Class<?> targetClass) {
// First, see if we have a cached value.
Object cacheKey = getCacheKey(method, targetClass);
Object cached = this.attributeCache.get(cacheKey);
if (cached !&#