How to force compile error with aspectJ pointcut mismatch

こ雲淡風輕ζ 提交于 2019-12-19 11:36:34

问题


I have the following aspectJ pointcut:

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

As you can see, this pointcut only matches methods, annotated with com.xxx.annotations.MyCustomAnnotation, which have 2 arguments - the first one is arbitrary and the second one must be of type Map<String, Object>.

Is there a way to configure the aspectj-maven-plugin to force compilation errors if it find methods that are annotated with com.xxx.annotations.MyCustomAnnotation, but don't match the signature * *(*,Map<String, Object>) ?

Or in other words, :

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

-> I want this to produce compile time error because Map<String, String> != Map<String, Object>


回答1:


You do it directly within an aspect, no need to configure it in AspectJ Maven plugin. Here is a little sample:

Marker annotation:

package de.scrum_master.app;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation {}

Sample application class:

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) {}
}

Aspect declaring compile error on method signature mismatch:

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";
}

When compiling this code you will see the following error in Eclipse as a code annotation and in the problem view (Maven console would show the same error when performing AspectJ Maven's compile goal):



来源:https://stackoverflow.com/questions/41698742/how-to-force-compile-error-with-aspectj-pointcut-mismatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!