1.定义切面
(1)@Aspect注解修饰切面类
(2)@Pointcut注解定义切点
(3)@Around注解切点代理方法
(4)@Before注解定义执行切点前所要执行的方法
(5)@After注解定义执行切点后所要执行的方法
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.Configuration;
@Aspect
@Configuration
public class MyLogAspect {
@Pointcut("execution(* controller.GoodsController.*(..)))")
private void myLogPointcut(){
}
@Before("myLogPointcut()")
private void before(JoinPoint joinPoint){
System.out.println("进入方法前:" + joinPoint.getSignature().getName());
}
@After("myLogPointcut()")
private void after(){
System.out.println("方法执行完。。。。。");
}
/*@AfterReturning(value = "myLogPointcut()", returning = "returnVal")
public void afterReturning(String returnVal){
System.out.println("后置通知,返回参数:" + returnVal);
}
@AfterThrowing(value = "myLogPointcut()", throwing = "e")
public void afterThrowing(Throwable e){
System.out.println("异常通知,异常信息:" + e.getMessage());
}*/
@Around("myLogPointcut()")
public Object around(ProceedingJoinPoint point){
//获得方法名称
Signature methodName = point.getSignature();
System.out.println("进入方法:" + methodName);
//让方法执行
Object obj = null;
try {
obj=point.proceed(point.getArgs());
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return obj;
}
}
2.执行切点对应的方法
调用Controller类里面的list方法
可以发现执行顺序是:around > before > list > after
3.总结说明
AOP的过程基本是首先定义一个切点,再对切点定义前后的执行方法,也比较简单。
本文介绍的切点只有execution,当然定义切点还有其他注解如@annotation,详细可以参考一下文章继续学习:
https://blog.csdn.net/Alinmei/article/details/123555553