Reputation: 34271
How to make an aspect that targets all public methods that belong to a class that is marked with specific annotation? In following method1() and method2() should be processed by the aspect and method3() should not be processed by the aspect.
@SomeAnnotation(SomeParam.class)
public class FooServiceImpl extends FooService {
public void method1() { ... }
public void method2() { ... }
}
public class BarServiceImpl extends BarService {
public void method3() { ... }
}
If I put annotations on method level, this aspect will work and match the method calls.
@Around("@annotation(someAnnotation)")
public Object invokeService(ProceedingJoinPoint pjp, SomeAnnotation someAnnotation)
throws Throwable {
// need to have access to someAnnotation's parameters.
someAnnotation.value();
}
I am using Spring and proxy based aspects.
Upvotes: 5
Views: 5023
Reputation: 4275
This works in Spring Boot 2:
@Around("@within(xyz)")
public Object method(ProceedingJoinPoint joinPoint, SomeAnnotation xyz) throws Throwable {
System.out.println(xyz.value());
return joinPoint.proceed();
}
Note that based on the method argument type (SomeAnnotation xyz
), Spring and AspectJ will know which annotation you are looking for, so the xyz
does not have to be the name of your annotation.
Upvotes: 2
Reputation: 49915
The following should work
@Pointcut("@target(someAnnotation)")
public void targetsSomeAnnotation(@SuppressWarnings("unused") SomeAnnotation someAnnotation) {/**/}
@Around("targetsSomeAnnotation(someAnnotation) && execution(* *(..))")
public Object aroundSomeAnnotationMethods(ProceedingJoinPoint joinPoint, SomeAnnotation someAnnotation) throws Throwable {
... your implementation..
}
Upvotes: 5
Reputation: 19
Using @target and reading the type level annotation with reflection works.
@Around("@target(com.example.SomeAnnotation)")
public Object invokeService(ProceedingJoinPoint pjp) throws Throwable {
Upvotes: 1