4.9 AOP-XML-环绕通知发布
戴着假发的程序员出品 抖音ID:戴着假发的程序员 欢迎关注
[查看视频教程]
所谓环绕通知就是在目标方法的前后可以通知增强,正因为这样的情况,所以环绕通知可以阻止方法的执行,或者修改方法的返回值。
环绕通知也可以传入一个参数ProceedingJoinPoint,ProceedingJoinPoint 是Joinpoint的一个子类,增强了一些方法,我们可以通过ProceedingJoinPoint 的proceed()调用被增强方法。
看案例:
业务方法:
1 /** 2 * @author 戴着假发的程序员 3 * @company http://www.boxuewa.com 4 * @description 5 */ 6 public class MessageBean { 7 //输出信息的业务方法 8 public String printMessage(String msg){ 9 System.out.println("MessageBean-printMessage:"+msg); 10 return msg; 11 } 12 }
在Aspect类中添加环绕通知的处理业务方法:
1 /** 2 * @author 戴着假发的程序员 3 * @company http://www.boxuewa.com 4 * @description 5 */ 6 public class DkAspect { 7 /** 8 * 环绕通知 9 */ 10 public Object round(ProceedingJoinPoint joinPoint) throws Throwable { 11 Object retVal = null; 12 System.out.println("--环绕通知开始--"); 13 //执行目标方法 14 try { 15 //这里可以根据条件判断是否要执行目标方法 16 retVal = joinPoint.proceed(); 17 //可以修改目标方法返回值 18 retVal = "环绕通知修改后的返回值"; 19 } catch (Throwable throwable) { 20 throwable.printStackTrace(); 21 } 22 System.out.println("--环绕通知结束--"); 23 return retVal; 24 } 25 }
在aop:config中添加环绕通知的配置:
1 <!-- AOP配置 --> 2 <aop:config> 3 <!-- 申明AspectBean,引用我们注册的dkAspect --> 4 <aop:aspect id="aspect" ref="dkAspcet"> 5 <!-- 声明一个切入点,命名为pointcut1 --> 6 <!-- xml中不能使用 && ,逻辑与要使用and,--> 7 <!-- 如果我们的before增强方法中传入了参数msg,我就要使用args(msg)限定切入点 --> 8 <aop:pointcut id="pointcut1" 9 expression="execution(* com.st.beans..*.*(..))"/> 10 <!-- 配置环绕通知 --> 11 <aop:around method="round" pointcut-ref="pointcut1"/> 12 </aop:aspect> 13 </aop:config>
执行业务方法测试:
1 ApplicationContext ac = 2 new ClassPathXmlApplicationContext("applicationContext.xml"); 3 MessageBean bean = ac.getBean(MessageBean.class); 4 String retVal = bean.printMessage("假发的穿戴技巧"); 5 System.out.println("业务方法的返回值:"+retVal);
结果:

我是戴着假发的程序员,分享技术,分享经验,如果要转载,请注明:出自戴着假发的程序员

浙公网安备 33010602011771号