springboot 自定義註解控制事務回滾
阿新 • • 發佈:2019-10-12
springboot 自定義註解通過切面控制方法主動拋異常達到事務回滾的目的
寫一個自定義註解
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
public @interface ThrowException {
public String value() default "";
}
寫一個切面控制,⚠️要用環繞通知
@Aspect @Component @Slf4j public class ThrowExectionAspect implements Ordered { //service層切點 @Pointcut("@within(com.hasl.isp.policyprovider.annotation.ThrowException)") public void excetionAspect() {} @Around("excetionAspect()") public Object around(ProceedingJoinPoint pjp) throws Throwable { Object result = pjp.proceed(pjp.getArgs()); if(result != null && result instanceof ReturnMsg) { ReturnMsg returnMsg = (ReturnMsg)result; if (returnMsg.getMsgList().size() > 0){ throw new BaseException("業務異常"); } } return result; } @Override public int getOrder() { return Integer.MAX_VALUE; } }
然後把自定義註解加到service實現類上面就可以了。