【问题标题】:How to force compile error with aspectJ pointcut mismatch如何使用 aspectJ 切入点不匹配强制编译错误
【发布时间】:2017-01-17 13:43:54
【问题描述】:

我有以下aspectJ切入点:

@Around(value="execution(* *(*,Map<String, Object>)) && @annotation(com.xxx.annotations.MyCustomAnnotation)")

如您所见,此切入点仅匹配使用 com.xxx.annotations.MyCustomAnnotation 注释的方法,这些方法有 2 个参数 - 第一个是任意的,第二个必须是 Map&lt;String, Object&gt; 类型。

如果发现使用 com.xxx.annotations.MyCustomAnnotation 注释但与签名 * *(*,Map&lt;String, Object&gt;) 不匹配的方法,是否有办法配置 aspectj-maven-plugin 以强制编译错误?

或者换句话说,:

@com.xxx.annotations.MyCustomAnnotation
public void test(String s, Map<String, String> m) {
   ...
}

-> 我希望这会产生编译时错误,因为 Map&lt;String, String&gt; != Map&lt;String, Object&gt;

【问题讨论】:

    标签: java maven aspectj aspectj-maven-plugin


    【解决方案1】:

    您可以直接在一个方面进行,无需在 AspectJ Maven 插件中进行配置。这是一个小例子:

    标记注释:

    package de.scrum_master.app;
    
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    
    @Retention(RetentionPolicy.RUNTIME)
    public @interface MyCustomAnnotation {}
    

    示例应用程序类:

    package de.scrum_master.app;
    
    import java.util.Map;
    
    public class Application {
        public void notAnnotated(String s, Map<String, Object> m) {}
    
        @MyCustomAnnotation
        public void correctSignature(String s, Map<String, Object> m) {}
    
        @MyCustomAnnotation
        public void wrongSignature(String s, Map<String, String> m) {}
    }
    

    在方法签名不匹配时声明编译错误的方面:

    package de.scrum_master.aspect;
    
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.DeclareError;
    
    @Aspect
    public class PointcutChecker {
        @DeclareError(
            "execution(* *(..)) && " +
            "@annotation(de.scrum_master.app.MyCustomAnnotation) && " +
            "!execution(* *(*, java.util.Map<String, Object>))"
        )
        static final String wrongSignatureError =
            "wrong method signature for @MyCustomAnnotation";
    }
    

    编译此代码时,您将在 Eclipse 中作为代码注释和问题视图看到以下错误(Maven 控制台在执行 AspectJ Maven 的compile 目标时会显示相同的错误):

    【讨论】:

    • P.S.:对于小问题,如果你想警告人们而不是失败构建,你也可以使用@DeclareWarning
    猜你喜欢
    • 1970-01-01
    • 2019-03-26
    • 2018-05-08
    • 1970-01-01
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多