切面的优先级

Last updated: ... / Reads: 32 Edit

在Spring AOP中,切面的执行顺序由其优先级决定。切面的优先级是通过实现org.springframework.core.Ordered接口或使用@Order注解来指定的。优先级值越低,切面的执行顺序越靠前。

以下是通过实现Ordered接口指定切面优先级的例子:

import org.springframework.core.Ordered;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class MyAspect1 implements Ordered {

    @Before("execution(* com.example.service.*.*(..))")
    public void beforeAdvice() {
        System.out.println("Before executing in MyAspect1");
    }

    @Override
    public int getOrder() {
        return 1; // 设置切面的优先级
    }
}

@Aspect
public class MyAspect2 implements Ordered {

    @Before("execution(* com.example.service.*.*(..))")
    public void beforeAdvice() {
        System.out.println("Before executing in MyAspect2");
    }

    @Override
    public int getOrder() {
        return 2; // 设置切面的优先级
    }
}

在这个例子中,MyAspect1 的优先级为1,MyAspect2 的优先级为2。因此,MyAspect1 将在 MyAspect2 之前执行。

如果使用@Order注解,可以在切面类上直接指定优先级,而不需要实现Ordered接口:

import org.springframework.core.annotation.Order;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
@Order(1)
public class MyAspect1 {

    @Before("execution(* com.example.service.*.*(..))")
    public void beforeAdvice() {
        System.out.println("Before executing in MyAspect1");
    }
}

@Aspect
@Order(2)
public class MyAspect2 {

    @Before("execution(* com.example.service.*.*(..))")
    public void beforeAdvice() {
        System.out.println("Before executing in MyAspect2");
    }
}

无论是使用Ordered接口还是@Order注解,都可以控制切面的执行顺序。


Comments

Make a comment