OrderAspect.java

  • AspectJ 传统语法概要

    如果说OOP的出现是把编码问题进行模块化,那么AOP就是把涉及到众多模块的某一类问题进行统一管理。

AspectJ

Spring AOP 属于运行时增强,而 AspectJ 是编译时增强。 Spring AOP 基于代理(Proxying),而 AspectJ 基于字节码操作(Bytecode Manipulation)。

image.png

切入点(pointcut)和通知(advice)

  1. /**
  2. * Created by zejian on 2017/2/15.
  3. * Blog : http://blog.csdn.net/javazejian [原文地址,请尊重原创]
  4. * 切面类
  5. */
  6. public aspect MyAspectJDemo {
  7. /**
  8. * 定义切点,日志记录切点
  9. */
  10. pointcut recordLog():call(* HelloWord.sayHello(..));
  11. /**
  12. * 定义切点,权限验证(实际开发中日志和权限一般会放在不同的切面中,这里仅为方便演示)
  13. */
  14. pointcut authCheck():call(* HelloWord.sayHello(..));
  15. /**
  16. * 定义前置通知
  17. *
  18. * before(参数):连接点函数{
  19. * 函数体
  20. * }
  21. */
  22. before():authCheck(){
  23. System.out.println("sayHello方法执行前验证权限");
  24. }
  25. /**
  26. * 定义后置通知
  27. * after(参数):连接点函数{
  28. * 函数体
  29. * }
  30. */
  31. after():recordLog(){
  32. System.out.println("sayHello方法执行后记录日志");
  33. }
  34. /**
  35. * 定义后置通知带返回值
  36. * after(参数)returning(返回值类型):连接点函数{
  37. * 函数体
  38. * }
  39. */
  40. after()returning(int x): get(){
  41. System.out.println("返回值为:"+x);
  42. }
  43. /**
  44. * 异常通知
  45. * after(参数) throwing(返回值类型):连接点函数{
  46. * 函数体
  47. * }
  48. */
  49. after() throwing(Exception e):sayHello2(){
  50. System.out.println("抛出异常:"+e.toString());
  51. }
  52. /**
  53. * 环绕通知 可通过proceed()控制目标函数是否执行
  54. * Object around(参数):连接点函数{
  55. * 函数体
  56. * Object result=proceed();//执行目标函数
  57. * return result;
  58. * }
  59. */
  60. Object around():aroundAdvice(){
  61. System.out.println("sayAround 执行前执行");
  62. Object result=proceed();//执行目标函数
  63. System.out.println("sayAround 执行后执行");
  64. return result;
  65. } /**
  66. * 定义前置通知!
  67. */
  68. before():authCheck(){
  69. System.out.println("sayHello方法执行前验证权限");
  70. }
  71. /**
  72. * 定义后置通知
  73. */
  74. after():recordLog(){
  75. System.out.println("sayHello方法执行后记录日志");
  76. }
  77. }

案例:recordLog()是函数名称,自定义的,* 表示任意返回值,接着就是需要拦截的目标函数,sayHello(..)的..,表示任意参数类型

  1. pointcut recordLog():call(* HelloWord.sayHello(..));

image.png