在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("后置通知");
}
}
测试结果
由测试结果可知,环绕通知开始,进入前置通知,然后到后置通知,最后环绕通知结束。