获取连接点签名和方法参数:JoinPoint 和ProceedingJoinPoint. 环绕通知中使用ProceedingJionPoint,其他通知中使用JoinPoint aop中所有的通知都写在通知类中,所以我就只写一下通知类中的内容
环绕通知中除了参数为ProceedingJoinPoint其他获取连接点签名和方法参数的方法与前置通知中的内容一致我就不再重复了
//环绕通知 public Object around(ProceedingJoinPoint pjp) { System.out.println("around before returning");//前置同通知 Object r=null; try { r= pjp.proceed();//调用目标方法,r时目标方法的返回值 } catch (Throwable e) { e.printStackTrace(); System.out.println("arround after throwing target");//例外通知 }finally { System.out.println("around after target");//最终通知; } System.out.println("around after returning target");//后置通知 return r; }下面配置文件中after-returning通知中的returning属性就是返回的返回值,要和method指向方法中object类型的参数名一致。 after-throwing中的throwing属性就是抛出的异常要和afterThrowing方法中的Throwable类型参数的参数名一致。
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id ="userDao" class="jee.pk1.UserDaoImpl"></bean> <bean id ="clientDao" class="jee.pk1.ClientDaoImpl"></bean> <!-- 这个bean保存通知内容 --> <bean id="daoAdvice" class="jee.pk1.DaoAdvice"></bean> <aop:config> <!-- 切面 --> <aop:aspect ref="daoAdvice"> <!-- 切入点 --> <aop:pointcut expression="execution(* jee.pk1.*Impl.*(..))" id="daoPointcut"/> <!-- 前置通知 --> <aop:after-returning pointcut-ref="daoPointcut" method="afterReturning" returning="r"/> <aop:after-throwing pointcut-ref="daoPointcut" method="daoPintcut" throwing="e"/> </aop:aspect> </aop:config> </beans>通知类:
//最终通知 //r是用于接收返回值的,当spring调用after的时候,spring就会将返回值传回来 public void after(JoinPoint jp,Object r) { System.out.println("after target"+"返回值:"+r); } //例外通知 //e用于保存目标方法抛出的异常 public void afterTrowing(JoinPoint jp,Throwable e) { System.out.println("after throwing"+"异常:"+e.getMessage()); }