Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AspectJ Pointcut to exclude annotation

I'm using Spring AOP for logging. I want to create a pointcut that applies to all methods except those that have a specific annotation, but I have no idea how to go about it. All I've found is how to include methods with an annotation.

like image 205
hoodakaushal Avatar asked Jun 27 '14 08:06

hoodakaushal


Video Answer


2 Answers

Sample annotation:

package de.scrum_master.app;

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

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

Driver Application:

package de.scrum_master.app;

public class Application {
    public static void main(String[] args) throws Exception {
        foo();
        bar();
        zot();
        baz();
    }

    @NoLogging public static void foo() {}
    public static void bar() {}
    @NoLogging public static void zot() {}
    public static void baz() {}
}

Aspect in native AspectJ syntax:

package de.scrum_master.aspect;

import de.scrum_master.app.NoLogging;

public aspect MyAspect {
    before() : execution(* *(..)) && !@annotation(NoLogging) {
        System.out.println(thisJoinPoint);
    }
}

Aspect in @AspectJ syntax (should also work in Spring AOP):

package de.scrum_master.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class MyAspectX {
    @Before("execution(* *(..)) && !@annotation(de.scrum_master.app.NoLogging)")
    public void logExceptAnnotated(JoinPoint thisJoinPoint) throws Throwable {
        System.out.println(thisJoinPoint);
    }
}

Both aspects are equivalent and yield the following output:

execution(void de.scrum_master.app.Application.main(String[]))
execution(void de.scrum_master.app.Application.bar())
execution(void de.scrum_master.app.Application.baz())
like image 66
kriegaex Avatar answered Oct 01 '22 23:10

kriegaex


This may help you

execution(* my.package.*.*(..)) && !execution(@annotation * my.package.*.*(..))
like image 20
ppuskar Avatar answered Oct 01 '22 23:10

ppuskar