Spring注解事务大致的实现原理

1. 自定义注解  @MyTransaction

/**
 * @author yangxj
 * @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.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. 织入

@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. 演示

Spring注解事务大致的实现原理

 

 

  

上一篇:搞懂Spring AOP的前世今生


下一篇:iOS解决按钮短时间内多次点击只触发一次事件方法