1. 自定义注解  @MyTransaction

/**
* @author yangxj
* @see org.springframework.transaction.annotation.SpringTransactionAnnotationParser
* @see org.springframework.transaction.interceptor.TransactionAttribute
* @see org.springframework.transaction.TransactionDefinition
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyTransaction {
String value() default "";
}

2. 自定义通知Advice

/**
* @author yangxj
*
* @see org.springframework.transaction.PlatformTransactionManager
* @see org.springframework.jdbc.datasource.DataSourceTransactionManager
* @see org.springframework.transaction.interceptor.TransactionInterceptor
*/
@Slf4j
public class MyTransactionInterceptor implements MethodInterceptor {

@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
log.info("拦截到事务方法:{}", methodInvocation.getMethod().getName());
try {
return methodInvocation.proceed();
// commit 提交事务
} catch (Exception e) {
// rollback 回滚事务
}
return null;
}
}

3. 织入

/**
* @author yangxj
* @see org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration
* @see org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor

*/
@Configuration
public class CommonConfiguration {
@Bean
public DefaultPointcutAdvisor myTransactionPointcutAdvisor() {
DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor(); // 切面 Aspect
advisor.setPointcut(new AnnotationMatchingPointcut(null, MyTransaction.class)); // 方法级别注解匹配 切入点 pointcut
advisor.setAdvice(new MyTransactionInterceptor()); // 通知 advice
return advisor;
}
}

4. 演示

 

 原理: 对应加了@Transactional 的方法,spring会为其生成一个代理bean,当调用方法时,使用事务管理器(TransactionManager)开启一个数据库连接并关闭autocommit,这样当方法异常时回滚否则提交事务

  

posted on 2021-06-03 11:24  yang希军  阅读(418)  评论(0)    收藏  举报