springboot 自定義註解控制事務回滾

springboot 自定義註解經過切面控制方法主動拋異常達到事務回滾的目的java

寫一個自定義註解spring

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
public @interface ThrowException {

    public String value() default "";

}

寫一個切面控制,⚠️要用環繞通知springboot

@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實現類上面就能夠了。ide

相關文章
相關標籤/搜索