java - AspectJ "around"和 "proceed"与 "before/after"

标签 java aop aspectj

假设您有三个建议:aroundbeforeafter

1) 在 around 建议中调用 proceed 时是否会调用 before/after, 还是将它们称为 before/after around 建议作为一个整体?

2) 如果我的 around 建议没有调用 proceedbefore/after 建议仍然会运行吗?

最佳答案

通过这个测试

@Aspect
public class TestAspect {
    private static boolean runAround = true;

    public static void main(String[] args) {
        new TestAspect().hello();
        runAround = false;
        new TestAspect().hello();
    }

    public void hello() {
        System.err.println("in hello");
    }

    @After("execution(void aspects.TestAspect.hello())")
    public void afterHello(JoinPoint joinPoint) {
        System.err.println("after " + joinPoint);
    }

    @Around("execution(void aspects.TestAspect.hello())")
    public void aroundHello(ProceedingJoinPoint joinPoint) throws Throwable {
        System.err.println("in around before " + joinPoint);
        if (runAround) {
            joinPoint.proceed();
        }
        System.err.println("in around after " + joinPoint);
    }

    @Before("execution(void aspects.TestAspect.hello())")
    public void beforeHello(JoinPoint joinPoint) {
        System.err.println("before " + joinPoint);
    }
}

我有以下输出

  1. 在执行前(void aspect.TestAspect.hello())
  2. 执行前(void aspect.TestAspect.hello())
  3. 你好
  4. 执行后(void aspect.TestAspect.hello())
  5. 在执行后(void aspect.TestAspect.hello())
  6. 在执行之前(void aspect.TestAspect.hello())
  7. 在执行后(void aspect.TestAspect.hello())

所以你可以看到在 @Around 注释中调用 proceed 时没有调用 before/after。

关于java - AspectJ "around"和 "proceed"与 "before/after",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18016503/

相关文章:

java - 当满足特定条件时,是否可以在 Java Stream 中使用谓词?

java - 在我的例子中避免魔数(Magic Number)的最佳方法

Java AOP 或 i18n 注释

java - 纯 AspectJ 加载时间编织不起作用

java - Spring AOP - 异常 : org. springframework.beans.factory.BeanDefinitionStoreException:

java - spring + aspectj,定义一个切面@Around

java - 语法错误,注释仅在源代码级别为 5.0 时可用 - Maven 中的 AspectJ

java - 从 Java 连接到托管在虚拟机中的 MYSQL 数据库

java - 如何在 war 包中配置 AspectJ 在 Weblogic 12c 中使用

java - 使用 Maven 更改模块版本