Search code examples
javamavenaspectjaspectj-maven-plugin

How to force compile error with aspectJ pointcut mismatch


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>


Solution

  • 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):

    Eclipse editor error marker

    Eclipse problem view