您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
10-xml方式实现aop-通知的种类(各种增强类型)
发布时间:2025-01-17 22:43:45编辑:雪饮阅读()
继上篇,接下来我们来玩玩后置增强。后置增强,见名知意,就是目标方法执行之后执行的。
在增强类MyAspect中新增后置增强方法
public void afterReturning(){
System.out.println("后置增强....");
}
然后Spring配置文件中切面配置中新增后置增强
<aop:aspect ref="myAspect">
<aop:before method="before" pointcut="execution(* sp21.aop.Target.save())"/>
<aop:after-returning method="afterReturning" pointcut="execution(* sp21.aop.Target.save())"/>
</aop:aspect>
再接下来我们完成环绕增强,环绕增强有点像是前置增强与后置增强的一个整合。
同样在增强类MyAspect中新增环绕增强方法
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕前增强....");
//切点方法
Object proceed=pjp.proceed();
System.out.println("环绕后增强....");
return proceed;
}
由于环绕增强有点像是前置增强与后置增强的一个整合,所以这里Spring配置文件中切面中先将前后置增强的织入先注释掉。然后写入环绕增强,以免影响控制台中的输出效果太乱了,不利用理解。
<aop:aspect ref="myAspect">
<!-- <aop:before method="before" pointcut="execution(* sp21.aop.Target.save())"/>
<aop:after-returning method="afterReturning" pointcut="execution(* sp21.aop.Target.save())"/>-->
<aop:around method="around" pointcut="execution(* sp21.aop.Target.save())"/>
</aop:aspect>
那么接下来就是异常抛出增强,同样在增强类MyAspect中新增异常抛出增强
public void afterThrowing(){
System.out.println("异常抛出增强......");
}
这里的异常抛出增加里面的异常指的是target中的被执行方法的异常,所以我们需要在Target中人为产生一个异常。例如我将Target类中的save方法修改如:
public void save() {
int i=1/0;
System.out.println("save running...");
}
然后再次在Spring配置文件中新增异常抛出增强
<aop:aspect ref="myAspect">
<!-- <aop:before method="before" pointcut="execution(* sp21.aop.Target.save())"/>
<aop:after-returning method="afterReturning" pointcut="execution(* sp21.aop.Target.save())"/>-->
<aop:around method="around" pointcut="execution(* sp21.aop.Target.save())"/>
<aop:after-throwing method="afterThrowing" pointcut="execution(* sp21.aop.Target.save())"/>
</aop:aspect>
这里需要说的一点就是异常抛出增强是从目标方法中抛出的异常,如果Spring产生了异常,这个就不好说了。
那么接下来就是最终增强了。就是不管是否抛异常,最终增强只要配置了都会执行的。
同样在增强类MyAspect中新增最终增强方法
public void after(){
System.out.println("最终增强....");
}
那么Spring配置文件中新增最终增强配置如
<aop:aspect ref="myAspect">
<!-- <aop:before method="before" pointcut="execution(* sp21.aop.Target.save())"/>
<aop:after-returning method="afterReturning" pointcut="execution(* sp21.aop.Target.save())"/>-->
<aop:around method="around" pointcut="execution(* sp21.aop.Target.save())"/>
<aop:after-throwing method="afterThrowing" pointcut="execution(* sp21.aop.Target.save())"/>
<aop:after method="after" pointcut="execution(* sp21.aop.Target.save())"/>
</aop:aspect>
关键字词:增强