溫馨提示×

spring aop中的通知怎么編寫

小樊
81
2024-09-02 05:50:51
欄目: 編程語言

在 Spring AOP 中,通知(Advice)是在目標方法執(zhí)行前、后或出現(xiàn)異常時執(zhí)行的代碼。要編寫一個通知,你需要創(chuàng)建一個類并實現(xiàn)相應的接口。以下是五種不同類型的通知及其實現(xiàn)方式:

  1. 前置通知(Before Advice):在目標方法執(zhí)行前執(zhí)行的通知。
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class BeforeAdvice {
    @Before("execution(* com.example.service.*.*(..))")
    public void beforeMethod(JoinPoint joinPoint) {
        System.out.println("前置通知:目標方法 " + joinPoint.getSignature().getName() + " 即將執(zhí)行");
    }
}
  1. 后置通知(After Advice):在目標方法執(zhí)行后執(zhí)行的通知。
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class AfterAdvice {
    @After("execution(* com.example.service.*.*(..))")
    public void afterMethod(JoinPoint joinPoint) {
        System.out.println("后置通知:目標方法 " + joinPoint.getSignature().getName() + " 已執(zhí)行完畢");
    }
}
  1. 返回通知(AfterReturning Advice):在目標方法正常返回后執(zhí)行的通知。
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class AfterReturningAdvice {
    @AfterReturning("execution(* com.example.service.*.*(..))")
    public void afterReturningMethod(JoinPoint joinPoint) {
        System.out.println("返回通知:目標方法 " + joinPoint.getSignature().getName() + " 已正常返回");
    }
}
  1. 異常通知(AfterThrowing Advice):在目標方法拋出異常后執(zhí)行的通知。
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class AfterThrowingAdvice {
    @AfterThrowing("execution(* com.example.service.*.*(..))")
    public void afterThrowingMethod(JoinPoint joinPoint) {
        System.out.println("異常通知:目標方法 " + joinPoint.getSignature().getName() + " 發(fā)生異常");
    }
}
  1. 環(huán)繞通知(Around Advice):在目標方法執(zhí)行前后都執(zhí)行的通知。
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class AroundAdvice {
    @Around("execution(* com.example.service.*.*(..))")
    public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("環(huán)繞通知:目標方法 " + joinPoint.getSignature().getName() + " 即將執(zhí)行");
        Object result = joinPoint.proceed();
        System.out.println("環(huán)繞通知:目標方法 " + joinPoint.getSignature().getName() + " 已執(zhí)行完畢");
        return result;
    }
}

注意:在實際項目中,你可能需要根據(jù)需求調(diào)整切點表達式(如 execution(* com.example.service.*.*(..)))以匹配你的目標方法。同時,確保你的 Aspect 類被 Spring 容器管理,例如通過添加 @Component 注解。

0