SpringAop+自定义注解实现声明式事务
Spring事务实现方式
@Override
@Transactional
public Integer insertUser() {
int i = userMapper.insertUser();
int j = 1/0;
return i;
}
spring中使用@Transactional来控制,当发生异常时,回滚当前所有事务。
这个注解是如何实现的呢?
先自定义一个注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyTransactional {
}
利用Aop的around去生效这个注解
@Aspect
@Component
public class MyTransactionalAop {
@Autowired
private TransactionaUtil transactionaUtil;
@Around(value = "@annotation(com.example.annotation.MyTransactional)")
public Object around(ProceedingJoinPoint joinPoint){
TransactionStatus begin = null;
try{
begin = transactionaUtil.begin();
Object result = joinPoint.proceed();
transactionaUtil.commit(begin);
return result;
} catch (Throwable throwable) {
if(begin!=null){
transactionaUtil.rollback(begin);
}
throwable.printStackTrace();
return 0;
}
}
}
使用的时候
@MyTransactional
public Integer insertUser() throws RuntimeException {
int i = userMapper.insertUser();
int j = 1/0;
return i;
}
这样就实现了自定义注解的事务异常回滚机制