天天看点

spring应用手册-AOP(注解)-(25)-切面发布-通知顺序[email protected]

戴着假发的程序员出品 抖音ID:戴着假发的程序员 欢迎关注

切面发布-通知顺序[email protected]

spring应用手册(第三部分)

有时我们可能在我们的业务上会增加多个相同类型的切面。这时就会有一个先后顺序问题。那么spring如何解决顺序问题呢?

在使用注解方式的环境下,我们可以通过@Order注解给切面排序,当然在没有@Order注解的情况下,多个切面本身是无顺序的(也就是按照默认顺序执行)。

这里要注意一个问题,@Order注解只有在@Aspect类上才生效,也就是下面的注解方式才生效:

@Component
@Aspect
@Order(1)
public class DkAspect1 {}
           
@Component
@Aspect
@Order(2)
public class DkAspect2 {}
           

所以如果我们有多个拦截需要排序,就需要将这个切面配置在不同的Aspect类中。

在同一个Aspect类中Advice方法是无法排序的,

我们看案例:

我们在一个Aspect类中准备三个前置通知,切入同一个切入点

/**
 * @author 戴着假发的程序员
 * 
 * @description
 */
@Component
@Aspect
public class DkAspect {
    @Pointcut("execution(* com.st.dk.demo8.service..*.*(..))")
    public void pointcut1(){}

    @Before("pointcut1()")
    public void beforeB(){
        System.out.println("--前置通知--BBB--");
    }
    @Before("pointcut1()")
    public void beforeA(){
        System.out.println("--前置通知--AAA--");
    }

    @Before("pointcut1()")
    public void beforeC(){
        System.out.println("--前置通知--CCC--");
    }
}
           

我们来看看自然顺序:

spring应用手册-AOP(注解)-(25)-切面发布-通知顺序[email protected]

很明显所谓自然顺序就是按照方法的名称的数字或者字母顺序排序的,并非方法的编写顺序。

我们来看看Order注解的源码:

package org.springframework.core.annotation;

@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE, java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.FIELD})
@java.lang.annotation.Documented
public @interface Order {
    int value() default 2147483647;
}
           

我们会发现Order中的value默认值是整形的最大值,而spring在对通知排序时,order中的value越小,优先级越高。

现在我们来使用Order注解控制我们的通知顺序:

/**
 * @author 戴着假发的程序员
 * 
 * @description
 */
@Component
@Aspect
@Order(1)//第一顺位
public class DKAspect1 {
    @Pointcut("execution(* com.st.dk.demo8.service..*.*(..))")
    public void pointcut1(){}

    @Before("pointcut1()")
    public void before(){
        System.out.println("前置通知:第一顺位");
    }
}

/**
 * @author 戴着假发的程序员
 * 
 * @description
 */
@Component
@Aspect
@Order(2)//第一顺位
public class DKAspect2 {
    @Pointcut("execution(* com.st.dk.demo8.service..*.*(..))")
    public void pointcut1(){}

    @Before("pointcut1()")
    public void before(){
        System.out.println("前置通知:第二顺位");
    }
}

/**
 * @author 戴着假发的程序员
 * 
 * @description
 */
@Component
@Aspect
@Order(3)//第一顺位
public class DKAspect3 {
    @Pointcut("execution(* com.st.dk.demo8.service..*.*(..))")
    public void pointcut1(){}

    @Before("pointcut1()")
    public void before(){
        System.out.println("前置通知:第三顺位");
    }
}

           

测试结果:

spring应用手册-AOP(注解)-(25)-切面发布-通知顺序[email protected]