即上一个最终通知的aspect代码上添加各种通知:

    1. package com.chentianyu.s04;
    2. import org.aspectj.lang.JoinPoint;
    3. import org.aspectj.lang.ProceedingJoinPoint;
    4. import org.aspectj.lang.annotation.*;
    5. import org.springframework.stereotype.Component;
    6. @Aspect
    7. @Component
    8. public class MyAspect {
    9. /**
    10. * 最终通知的规范
    11. * 1.访问权限是public
    12. * 2.方法没有返回值
    13. * 3.方法名称自定义
    14. * 4.方法没有参数,如果有也只能是JoinPoint(前置通知说过有JoinPoint,它必须是整个参数的第一个)
    15. * 5.使用@After注解,表明是最终通知
    16. * value: 指定切入点表达式
    17. */
    18. @Before(value = "execution(* com.chentianyu.s04.*.*(..))")
    19. public void myBefore(JoinPoint jp){
    20. System.out.println("前置通知功能....");
    21. }
    22. @AfterReturning(value = "execution(* com.chentianyu.s04.*.*(..))",returning = "obj")
    23. public void myAfterReturning(Object obj/*目标方法的返回值*/){
    24. obj.toString().toUpperCase();
    25. }
    26. @After(value = "execution(* com.chentianyu.s04.*.*(..))")
    27. public void myAfter(){
    28. System.out.println("最终通知的功能...");
    29. }
    30. @Around(value = "execution(* com.chentianyu.s04.*.*(..))")
    31. public Object myAround(ProceedingJoinPoint pjp) throws Throwable {
    32. //前切功能实现
    33. System.out.println("环绕通知中的前置功能实现...");
    34. //目标方法调用
    35. Object obj = pjp.proceed(pjp.getArgs());
    36. //后切功能实现
    37. System.out.println("环绕通知中的后置功能实现...");
    38. return obj;
    39. }
    40. }

    你还可以定义俩个相同的通知和若干个

    1. @Before(value = "execution(* com.chentianyu.s04.*.*(..))")
    2. public void myBefore(JoinPoint jp){
    3. System.out.println("前置通知功能....");
    4. }
    5. @Before(value = "execution(* com.chentianyu.s04.*.*(..))")
    6. public void myBefore1(JoinPoint jp){
    7. System.out.println("前置通知功能....!!!");
    8. }

    前置通知不一定先被执行,所以看输出

    1. @Test
    2. public void test04(){
    3. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("s04/applicationContext.xml");
    4. com.chentianyu.s04.SomeService someService = (com.chentianyu.s04.SomeService) applicationContext.getBean("someServiceImpl");//接口的实现类名称
    5. String s = someService.doSome("张三", 22);
    6. System.out.println("在测试方法中的目标方法返回值:" + s);
    7. }
    1. 环绕通知中的前置功能实现...
    2. 前置通知功能....
    3. 前置通知功能....!!!
    4. doSome业务方法被执行了...张三
    5. 最终通知的功能...
    6. 环绕通知中的后置功能实现...
    7. 在测试方法中的目标方法返回值:abcd

    这是最优顺序