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