【问题标题】:aspectj: why advice cannot be applied?aspectj:为什么不能应用建议?
【发布时间】:2012-08-21 11:02:12
【问题描述】:

我已经创建了非常基本的 aspectJ 项目。我不知道为什么不能应用建议。

注释

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)  
@Target(ElementType.METHOD)  
@Documented  
public @interface Conditional {  
    String value();  
}  

和 aspectJ 类:

@Aspect
public class AspectE {

    @Around("call(@Conditional * *.*(..)) && @annotation(conditional)" )
    public Object condition(ProceedingJoinPoint joinPoint, Conditional conditional) throws Throwable {

        System.out.println("entry point says hello!");
        return joinPoint.proceed();
    }
}

主要:

public class Main {

    @Conditional("")
    public static void main(String[] args) {
        System.out.println("main good morning");
    }
}

你能告诉我我应该改变什么来接收这两条消息吗?

【问题讨论】:

    标签: java aspectj


    【解决方案1】:

    我认为这是因为 call(@Conditional * *.*(..)) 基本上编织了调用者,在这种特定情况下调用者是命令行,因此没有编织发生。

    您可能应该将其更改为执行,这应该可以。

    @Around("execution(@Conditional * *.*(..)) && @annotation(conditional)" )

    【讨论】:

    • 我已将其更改为"execution(@EntryPoint * *.*(..))",令人惊讶的是它可以正常工作。你能解释一下为什么吗?我觉得很有趣。
    • 是的,如果你有call..,aspectj 会编织调用者,所以如果method1 调用method2,那么method1 将被更改为有@Around 围绕它的逻辑,method2 将保持不变。在您的情况下,method2 恰好是根本不会触及的主要方法。
    【解决方案2】:

    您应该使用AspectJ weaver 以便将您的切面AspectE 应用于Java 类Main。如果您使用的是 Maven,我建议您使用 aspectj-maven-plugin

    【讨论】:

    • 在使用 Maven 之前,我想通过 eclipse 编译器来编译项目。可以看到不基于注释的建议。有什么建议吗?
    【解决方案3】:
    1. 您的建议必须proceed(conditional),或者,如果您不需要将对象绑定到变​​量,请移除绑定。

    2. 您的切入点匹配问题是您的应用程序内部没有调用main 的地方(Java 命令行会这样做),只有执行该方法的地方,因此您想更改该部分你的切入点到execution(@Conditional * *.*(..))

    3. 为简化操作,您可以删除切入点的任何部分,因为这两个切入点都将匹配,而无需通过&& 冗余连接它们。

    因此,AspectJ 语法中最简单的切面版本是:

    public aspect AspectE {
        Object around() : @annotation(Conditional) {
            System.out.println("entry point says hello!");
            return proceed();
        }
    }
    

    【讨论】:

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