spring aop中的通知怎么编写

   2024-09-30 6820
核心提示:在 Spring AOP 中,通知(Advice)是在目标方法执行前、后或出现异常时执行的代码。要编写一个通知,你需要创建一个类并实现相应

在 Spring AOP 中,通知(Advice)是在目标方法执行前、后或出现异常时执行的代码。要编写一个通知,你需要创建一个类并实现相应的接口。以下是五种不同类型的通知及其实现方式:

前置通知(Before Advice):在目标方法执行前执行的通知。
import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;@Aspectpublic class BeforeAdvice {    @Before("execution(* com.example.service.*.*(..))")    public void beforeMethod(JoinPoint joinPoint) {        System.out.println("前置通知:目标方法 " + joinPoint.getSignature().getName() + " 即将执行");    }}
后置通知(After Advice):在目标方法执行后执行的通知。
import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.Aspect;@Aspectpublic class AfterAdvice {    @After("execution(* com.example.service.*.*(..))")    public void afterMethod(JoinPoint joinPoint) {        System.out.println("后置通知:目标方法 " + joinPoint.getSignature().getName() + " 已执行完毕");    }}
返回通知(AfterReturning Advice):在目标方法正常返回后执行的通知。
import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.AfterReturning;import org.aspectj.lang.annotation.Aspect;@Aspectpublic class AfterReturningAdvice {    @AfterReturning("execution(* com.example.service.*.*(..))")    public void afterReturningMethod(JoinPoint joinPoint) {        System.out.println("返回通知:目标方法 " + joinPoint.getSignature().getName() + " 已正常返回");    }}
异常通知(AfterThrowing Advice):在目标方法抛出异常后执行的通知。
import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.AfterThrowing;import org.aspectj.lang.annotation.Aspect;@Aspectpublic class AfterThrowingAdvice {    @AfterThrowing("execution(* com.example.service.*.*(..))")    public void afterThrowingMethod(JoinPoint joinPoint) {        System.out.println("异常通知:目标方法 " + joinPoint.getSignature().getName() + " 发生异常");    }}
环绕通知(Around Advice):在目标方法执行前后都执行的通知。
import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;@Aspectpublic class AroundAdvice {    @Around("execution(* com.example.service.*.*(..))")    public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {        System.out.println("环绕通知:目标方法 " + joinPoint.getSignature().getName() + " 即将执行");        Object result = joinPoint.proceed();        System.out.println("环绕通知:目标方法 " + joinPoint.getSignature().getName() + " 已执行完毕");        return result;    }}

注意:在实际项目中,你可能需要根据需求调整切点表达式(如 execution(* com.example.service.*.*(..)))以匹配你的目标方法。同时,确保你的 Aspect 类被 Spring 容器管理,例如通过添加 @Component 注解。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号