AspectJ Pointcut exclude annotation

I am 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 do this. All I have found is to include methods with annotation.

+6
source share
2 answers

Annotation Example:

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 AspectJ source 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 give the following result:

 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()) 
+10
source

It can help you.

 execution(* my.package.*.*(..)) && !execution(@annotation * my.package.*.*(..)) 
0
source

Source: https://habr.com/ru/post/971410/


All Articles