1 package com.bjpowernode.ba03; 2 3 import org.aspectj.lang.JoinPoint; 4 import org.aspectj.lang.ProceedingJoinPoint; 5 import org.aspectj.lang.annotation.AfterReturning; 6 import org.aspectj.lang.annotation.Around; 7 import org.aspectj.lang.annotation.Aspect; 8 9 import java.util.Date; 10 11 @Aspect 12 public class MyAspect { 13 /** 14 * 环绕通知方法的定义格式 15 * 1. public 16 * 2. 必须有一个返回值,推荐使用Object 17 * 3. 方法名称自定义 18 * 4. 方法有参数,固定的参数ProceedingJoinPoint 19 */ 20 /** 21 * @Around:环绕通知 22 * 属性:value 切入点表达式 23 * 位置 在方法的定义前后执行 24 * 25 * 特点: 26 * 1. 他是功能最强的通知 27 * 2. 在目标方法的前后都能增强功能 28 * 3. 控制目标方法是否被调用执行 29 * 4. 修改原来的目标方法的执行结果,影响最后的调用结果 30 * 环绕通知等同于JDK动态代理的InvocationHandler接口 31 * 32 * 参数:ProceedingJoinPoint 就等同于Method,作用:执行目标方法的 33 * 返回值:就是目标方法的执行结果,可以被修改。 34 * 35 * 环绕通知:经常做事务,在目标方法之前开启事务,执行目标方法,目标方法执行完成后结束事务 36 */ 37 @Around(value="execution(* *First(String,Integer))" ) 38 public Object myAround(ProceedingJoinPoint pjp) throws Throwable { 39 //获取目标方法的参数 40 String name=""; 41 Object args[] = pjp.getArgs(); 42 if(args!=null && args.length>1){ 43 Object arg=args[0]; 44 name = (String) arg; 45 } 46 //实现环绕通知 47 Object result = null; 48 System.out.println("环绕通知:在目标方法之前输出时间"+new Date()); 49 //1. 目标方法调用 50 Object[] objs = pjp.getArgs(); 51 if("虎虎虎1".equals(name)){//可以控制目标方法的执行 52 result = pjp.proceed();//Method.invoke;Object result = doFirst(); 执行目标方法 53 } 54 //2. 在目标方法之后加入功能 55 System.out.println("环绕通知:在目标方法之后,提交事务"); 56 //返回目标方法执行的结果,可以修改目标方法的执行结果,影响目标方法的最终返回值 57 return result+"ddd"; 58 59 } 60 }
1 package com.bjpowernode; 2 3 import com.bjpowernode.ba03.SomeService; 4 import org.junit.Test; 5 import org.springframework.context.ApplicationContext; 6 import org.springframework.context.support.ClassPathXmlApplicationContext; 7 8 public class MyTest01 { 9 @Test 10 public void test01(){ 11 ApplicationContext ac= new ClassPathXmlApplicationContext("ApplicationContext.xml"); 12 SomeService someService = (SomeService) ac.getBean("myService"); 13 someService.doSome("张三",33); 14 someService.doOther("李四",21); 15 String res = someService.doFirst("虎虎虎" ,12); 16 System.out.println(res); 17 } 18 }
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> 5 <bean id="myService" class="com.bjpowernode.ba03.SomeServiceImpl"/> 6 <bean id="myAspect" class="com.bjpowernode.ba03.MyAspect"/> 7 <aop:aspectj-autoproxy/> 8 </beans>
执行了doSome方法!
执行了doOther方法!
环绕通知:在目标方法之前输出时间Thu Mar 04 22:35:43 CST 2021
环绕通知:在目标方法之后,提交事务
nullddd