上一篇文章介绍了SpringAOP的概念以及简单使用:SpringAOP概念及其使用
在springAOP中有五种通知,环绕通知是最为强大的通知。它能够让你编写的逻辑将被通知的目标方法完全包装起来。实际上就像在一个通知方法中同时编写前置通知和后置通知。
本片文章具体讲解环绕通知的使用。
使用注解
使用环绕通知定义切面:
@Aspect
public class AudienceAround {
//使用@Pointcut注解声明频繁使用的切入点表达式
@Pointcut("execution(* com.wqh.concert.Performance.perform(..))")
public void performance(){}
@Around("performance()")
public void watchPerformance(ProceedingJoinPoint joinPoint){
try {
System.out.println("Silencing cell phones");
System.out.println("Taking seats");
joinPoint.proceed();
System.out.println("Demanding a refund");
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
可以看到在上面的代码中,定义通知的时候在通知方法中添加了入参:ProceedingJoinPoint。在创建环绕通知的时候,这个参数是必须写的。因为在需要在通知中使用ProceedingJoinPoint.proceed()方法调用被通知的方法。
另外,如果忘记调用proceed()方法,那么通知实际上会阻塞对被通知方法的调用。
在XML中定义
首先去掉上面类的所有注解:这里为了区别就重新创建一个类
public class AudienceAroundXML {
public void watchPerformance(ProceedingJoinPoint joinPoint){
try {
System.out.println("Silencing cell phones");
System.out.println("Taking seats");
joinPoint.proceed();
System.out.println("Demanding a refund");
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
配置:
<!--声明bean-->
<bean name="audienceAroundXML" class="com.wqh.concert.AudienceAroundXML"/>
<!--配置切面及通知-->
<aop:config>
<aop:aspect ref="audienceAroundXML">
<aop:pointcut id="performance"
expression="execution(* com.wqh.concert.Performance.perform(..))"/>
<aop:around method="watchPerformance" pointcut-ref="performance"/>
</aop:aspect>
</aop:config>