戴着假发的程序员出品 抖音ID:戴着假发的程序员 欢迎关注
AOP-XML-多个通知的执行顺序
spring应用手册(第四部分)
有时我们可能在我们的业务上会增加多个相同类型的切面。这时就会有一个先后顺序问题。那么spring如何解决顺序问题呢?
注解方式下Aspect中的方法默认是按照自然顺序排序的,我们可以在Aspect类上使用@Order指定顺序,在XML配置方式中是按照配置的先后顺序执行的。
看案例:
我们在Aspect中添加三个前置通知:
/**
* @author 戴着假发的程序员
* @company http://www.boxuewa.com
* @description
*/
public class DkAspect {
//前置通知1
public void before1(JoinPoint joinPoint){
System.out.println("前置通知-11");
}
//前置通知2
public void before2(JoinPoint joinPoint){
System.out.println("前置通知-22");
}
//前置通知3
public void before3(JoinPoint joinPoint){
System.out.println("前置通知-33");
}
}
在aop:config中按照2-3-1的顺序配置三个通知:
<!-- AOP配置 -->
<aop:config>
<!-- 申明AspectBean,引用我们注册的dkAspect -->
<aop:aspect id="aspect" ref="dkAspcet">
<!-- 声明一个切入点,命名为pointcut1 -->
<aop:pointcut id="pointcut1"
expression="execution(* com.st.beans..*.*(..))"/>
<aop:before method="before2" pointcut-ref="pointcut1"/>
<aop:before method="before3" pointcut-ref="pointcut1"/>
<aop:before method="before1" pointcut-ref="pointcut1"/>
</aop:aspect>
</aop:config>
执行业务方法进行测试得到结果:
注意,同一个通知方法也可配置多次,如果配置多次,spring就会执行多次。