相关注解

    @EnableAspectJAutoProxy
    @Aspect
    @Pointcut
    @Before
    @After
    @Around
    @AfterReturning
    @AfterThrowing

    添加依赖

    1. <dependency>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-starter-aop</artifactId>
    4. </dependency>

    spring声明支持aop

    1. @MapperScan("com.my.learn.mapper")
    2. @SpringBootApplication
    3. @EnableAspectJAutoProxy //开启spring对注解aop的支持
    4. public class MyBatisLearnApplication {
    5. public static void main(String[] args) {
    6. SpringApplication.run(MyBatisLearnApplication.class);
    7. }
    8. }

    定义切面

    1. @Aspect
    2. @Component
    3. public class RequestAspectConfig {
    4. /**
    5. * 在注解中如何使⽤呢?
    6. * 第⼀步:编写⼀个⽅法
    7. * 第⼆步:在⽅法使⽤@Pointcut注解
    8. * 第三步:给注解的value属性提供切⼊点表达式
    9. * 细节:
    10. * 1.在引⽤切⼊点表达式时,必须是⽅法名+(),例如"pointcut()"。
    11. * 2.在当前切⾯中使⽤,可以直接写⽅法名。在其他切⾯中使⽤必须是全限定⽅法名。
    12. */
    13. @Pointcut("execution(* com.my.learn.controller.*.*(..))")
    14. public void pointcut() {
    15. }
    16. @Before("pointcut()")
    17. public void beforePrintLog(JoinPoint jp) {
    18. Object[] args = jp.getArgs();
    19. System.out.println("前置通知:beforePrintLog,参数是:" + Arrays.toString(args));
    20. }
    21. @AfterReturning(value = "pointcut()", returning = "rtValue")
    22. public void afterReturningPrintLog(Object rtValue) {
    23. System.out.println("后置通知:afterReturningPrintLog,返回值是:" + rtValue);
    24. }
    25. @AfterThrowing(value = "pointcut()", throwing = "e")
    26. public void afterThrowingPrintLog(Throwable e) {
    27. System.out.println("异常通知:afterThrowingPrintLog,异常是:" + e);
    28. }
    29. @After("pointcut()")
    30. public void afterPrintLog() {
    31. System.out.println("最终通知:afterPrintLog");
    32. }
    33. /**
    34. * 环绕通知
    35. * @param pjp
    36. * @return
    37. */
    38. @Around("pointcut()")
    39. public Object aroundPrintLog(ProceedingJoinPoint pjp) {
    40. //定义返回值
    41. Object rtValue = null;
    42. try {
    43. //前置通知
    44. System.out.println("前置通知");
    45. //1.获取参数
    46. Object[] args = pjp.getArgs();
    47. //2.执⾏切⼊点⽅法
    48. rtValue = pjp.proceed(args);
    49. //后置通知
    50. System.out.println("后置通知");
    51. } catch (Throwable t) {
    52. //异常通知
    53. System.out.println("异常通知");
    54. t.printStackTrace();
    55. } finally {
    56. //最终通知
    57. System.out.println("最终通知");
    58. }
    59. return rtValue;
    60. }
    61. }