【问题标题】:AspectJ "around" and "proceed" with "before / after"AspectJ“围绕”和“继续”与“之前/之后”
【发布时间】:2013-08-03 16:49:33
【问题描述】:

假设您有三个建议:around、before 和 after。

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

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

【问题讨论】:

  • 我想这很容易测试;是否存在阻止您这样做的具体问题?
  • @DaveNewton 好吧,我不是 Java 开发人员,也没有可用的环境。我正在将 AOP 范式移植到另一种语言中,并四处寻找有关现有工具的文档。我认为最好请教专家,但如果没有人可以帮助我,我最终会这样做。

标签: java aop aspectj


【解决方案1】:

通过这个测试

@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。

【讨论】:

  • 这样您就可以看到,当从 @Around 注释中调用继续时,之前/之后没有被调用。是不是正好相反?
【解决方案2】:

问:2)如果我的周围建议没有调用继续,之前/之后的建议是否会运行?

Ans:如果你没有在你的周围建议中调用继续,你的之前的建议以及你的代码执行将被跳过,但你的之后的建议将被执行。但是如果你的之后的建议使用该方法中的任何值,那么一切都将为空.所以实际上根本没有使用该建议的意义...

希望,我有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多