即上一个最终通知的aspect代码上添加各种通知:
package com.chentianyu.s04;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.*;import org.springframework.stereotype.Component;@Aspect@Componentpublic class MyAspect {/*** 最终通知的规范* 1.访问权限是public* 2.方法没有返回值* 3.方法名称自定义* 4.方法没有参数,如果有也只能是JoinPoint(前置通知说过有JoinPoint,它必须是整个参数的第一个)* 5.使用@After注解,表明是最终通知* value: 指定切入点表达式*/@Before(value = "execution(* com.chentianyu.s04.*.*(..))")public void myBefore(JoinPoint jp){System.out.println("前置通知功能....");}@AfterReturning(value = "execution(* com.chentianyu.s04.*.*(..))",returning = "obj")public void myAfterReturning(Object obj/*目标方法的返回值*/){obj.toString().toUpperCase();}@After(value = "execution(* com.chentianyu.s04.*.*(..))")public void myAfter(){System.out.println("最终通知的功能...");}@Around(value = "execution(* com.chentianyu.s04.*.*(..))")public Object myAround(ProceedingJoinPoint pjp) throws Throwable {//前切功能实现System.out.println("环绕通知中的前置功能实现...");//目标方法调用Object obj = pjp.proceed(pjp.getArgs());//后切功能实现System.out.println("环绕通知中的后置功能实现...");return obj;}}
你还可以定义俩个相同的通知和若干个
@Before(value = "execution(* com.chentianyu.s04.*.*(..))")public void myBefore(JoinPoint jp){System.out.println("前置通知功能....");}@Before(value = "execution(* com.chentianyu.s04.*.*(..))")public void myBefore1(JoinPoint jp){System.out.println("前置通知功能....!!!");}
前置通知不一定先被执行,所以看输出
@Testpublic void test04(){ApplicationContext applicationContext = new ClassPathXmlApplicationContext("s04/applicationContext.xml");com.chentianyu.s04.SomeService someService = (com.chentianyu.s04.SomeService) applicationContext.getBean("someServiceImpl");//接口的实现类名称String s = someService.doSome("张三", 22);System.out.println("在测试方法中的目标方法返回值:" + s);}
环绕通知中的前置功能实现...前置通知功能....前置通知功能....!!!doSome业务方法被执行了...张三最终通知的功能...环绕通知中的后置功能实现...在测试方法中的目标方法返回值:abcd
这是最优顺序
