前置通知、环绕通知和后置通知

在Java中,AOP(Aspect-Oriented Programming,面向切面编程)是一种编程范式,它允许开发者将横切关注点(如日志记录、事务管理、安全等)从业务逻辑代码中分离出来,从而提高代码的模块性和可重用性。在Spring框架中,AOP的实现主要通过代理模式来完成。Spring AOP提供了三种类型的通知(Advice):前置通知(Before advice)、环绕通知(Around advice)和后置通知(After advice)。

 案例:

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Slf4j
/*AOP的类*/
@Aspect
/*组件*/
@Component
public class LogAspect {
    /*
    定义一个切点
    */
    @Pointcut("execution(public * com.jiawa..*Controller.*(..))")
    public void pointcut(){

    }

    /*
    前置通知
    */
    @Before("pointcut()")
    public void doBefore(JoinPoint joinPoint){
        log. info("前置通知");
    }

    /*
    * 环绕通知
    * */
    @Around("pointcut()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        log. info("环绕通知开始");
        Object result = proceedingJoinPoint.proceed();
        log. info("环绕通知结束");
        return result;
    }

    /*
    * 后置通知
    * */
    @After("pointcut()")
    public void doAfter(JoinPoint joinPoint){
        log.info("后置通知");
    }
}

测试结果

 由测试结果可知,环绕通知开始,进入前置通知,然后到后置通知,最后环绕通知结束

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值