首页 > 解决方案 > 如何更改由相同注释(例如 AspectJ 中的 @Around)注释的两个或多个建议的执行顺序?

问题描述

这是我的代码:

@Pointcut("execution(* *(..))")
public void cutPointToken() {}

@Pointcut("execution(* *(..))")
public void cutPointEmptyParam() {}

@Around("cutPointToken()")
public Object authenticateToken(ProceedingJoinPoint joinPoint) throws Throwable {
    LOGGER.info("authenticate -- start --");
    ...
    Object o = joinPoint.proceed();
    LOGGER.info("authenticate -- end --");
    return o;
}

@Around("cutPointEmptyParam()")
public Object checkParameter(ProceedingJoinPoint joinPoint) throws Throwable {
    LOGGER.info("check param -- start --");
    ...
    Object o = joinPoint.proceed();
    LOGGER.info("check param -- end --");
    return o;
}

我有:

authenticate -- start --
check param -- start --
...
check param -- end --
authenticate -- end --

预期的:

check param -- start --
authenticate -- start --
...
authenticate -- end --
check param -- end --

如何更改这两种方法的执行顺序?

在方法上和另一个上尝试了@Order注释,但它不起作用。@Order(1)checkParameter@Order(2)

标签: javaspringannotationsaspectjspring-aop

解决方案


使用@Order注释的想法是正确的,但是,将其放在类级别,如文档7.2.4.7 建议排序状态。

这是通过实现 org.springframework.core 以正常的 Spring 方式完成的。方面类中的有序接口或使用 Order 注释对其进行注释。

由于未注册为 bean,因此在带有注释的方法上的放置@Aspect将不起作用。在1.9.2中查找@Order注释。@Autowired部分。

@Order注释可以在目标类级别声明,也可以在方法上声明@Bean......

@Aspect
@Order(1)
public class CheckParameterAspect {

    @Around("cutPointEmptyParam()")
    public Object checkParameter(ProceedingJoinPoint joinPoint) throws Throwable {
        //...
    }
}

@Aspect
@Order(2)
public class AuthenticateTokenAspect {

    @Around("cutPointToken()")
    public Object authenticateToken(ProceedingJoinPoint joinPoint) throws Throwable {
        //...
    }
}

编辑:订购0似乎是可能的。


推荐阅读