戴着假发的程序员出品 抖音ID:戴着假发的程序员 欢迎关注
AOP-XML-advisor方式-多通知执行顺序
spring应用手册(第四部分)
在Advisor方式中我们也会遇到多个通知顺序问题,在这里spring提供的解决方案是:我们可以让我们通知类实现接口Ordered,通过实现其中的方法getOrder方法来指定通知的执行顺序,order越小的优先级越高。当没有指定Order时,默认按照自认顺序执行(自然顺序就是加载顺序)。
看我们的案例:
我们准备两个前置通知类,并且都是先Ordered接口:
/**
* @author 戴着假发的程序员
* @company http://www.boxuewa.com
* @description
*/
public class DkBeforeAdvice1 implements MethodBeforeAdvice, Ordered {
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println("前置通知1");
}
@Override
public int getOrder() {
return 1;
}
}
/**
* @author 戴着假发的程序员
* @company http://www.boxuewa.com
* @description
*/
public class DkBeforeAdvice2 implements MethodBeforeAdvice, Ordered {
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println("前置通知2");
}
@Override
public int getOrder() {
return 2;
}
}
配置两个通知:
<!-- 两个通知类注册 -->
<bean id="beforeAdvice1" class="com.st.advices.DkBeforeAdvice1"/>
<bean id="beforeAdvice2" class="com.st.advices.DkBeforeAdvice2"/>
<!-- AOP配置 -->
<aop:config>
<!-- 声明一个切入点,命名为pointcut1 -->
<aop:pointcut id="pointcut1"
expression="execution(* com.st.beans..*.*(..))"/>
<!-- 两个前置通知 -->
<aop:advisor advice-ref="beforeAdvice2" pointcut-ref="pointcut1"/>
<aop:advisor advice-ref="beforeAdvice1" pointcut-ref="pointcut1"/>
</aop:config>
执行业务类测试: