Spring- 5AOP

面向切面編程的一種方式
1 配置掃描
在這裏插入圖片描述
2 通過註解切面
在這裏插入圖片描述

 */
@Aspect
@Component
public class Aop {

    private void aop(JoinPoint joinPoint, String s) {
        Signature signature = joinPoint.getSignature();
        String methonName = signature.getName();
        Object[] args = joinPoint.getArgs();
        System.out.println(getClass().getName() + s + ",方法名字:" + methonName + ",參數列表:" + List.of(args));
    }

    @Pointcut(value = "execution( public *  spring.anntation.aop.dynamicProxy.CalculateImpl.*(..))")
    private void beforeDoPoint() {
    }

    @Around(value = "beforeDoPoint()")
    private Object around(ProceedingJoinPoint proceedingJoinPoint) {
        System.out.println("環繞執行方法前");
        Signature signature = proceedingJoinPoint.getSignature();
        //方法名字
        String mothodName = signature.getName();
        //參數列表
        Object[] args = proceedingJoinPoint.getArgs();

        Object result = null;
        try {
            //方法執行
            result = proceedingJoinPoint.proceed(args);
            System.out.println("環繞執行方法返回" + result);
        } catch (Throwable e) {
            e.printStackTrace();
            String message = e.getMessage();
            if (message == null) {
                message = e.getCause().getMessage();
            }
            System.out.println("環繞方法異常" + message);
            //拋出去讓afterThrowing捕捉
            throw new RuntimeException(message);
        } finally {
            System.out.println("環繞方法後置");
        }
        return result;

    }

    @AfterThrowing(value = "beforeDoPoint()", throwing = "e")
    private void beforeThrow(JoinPoint joinPoint, Exception e) {
        aop(joinPoint, "異常通知");
        System.out.println(e);
//        throw new RuntimeException(e);
    }

    @AfterReturning(value = "beforeDoPoint()", returning = "result")
    public Object afterReturn(JoinPoint joinPoint, Object result) {
        aop(joinPoint, "返回通知");
        System.out.println("返回通知" + result);
        return result;
    }

    @After(value = "beforeDoPoint()")
    public void afterDo(JoinPoint joinPoint) {
        aop(joinPoint, "後置通知");
    }


    @Before(value = "beforeDoPoint()")
    public void beforeDo3(JoinPoint joinPoint) {
        aop(joinPoint, "前置通知");
    }

//    @Before(value = "execution(public  int  spring.anntation.aop.dynamicProxy.CalculateImpl.add(int, int))")
//    public void beforeDo2(JoinPoint joinPoint) {
//        Signature signature = joinPoint.getSignature();
//        String methonName = signature.getName();
//        Object[] args = joinPoint.getArgs();
//        System.out.println(getClass().getName() + "前置通知,方法名字:" + methonName + ",參數列表:" + List.of(args));
//    }


}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章