Following aspect code would advice a target method annotated with @AnnotationName
@Component
@Aspect
public class SomeMethodAspect {
@Pointcut("@annotation(annotationName) && within(so.qn69016852..*)")
private void someMethod(AnnotationName annotationName) {}
@Around("someMethod(annotationName)")
public Object aroundSomeMethod(ProceedingJoinPoint pjp,AnnotationName annotationName) throws Throwable
{
System.out.println(annotationName.someString());
System.out.println(annotationName.someBoolean());
return pjp.proceed();
}
}
Couple of corrections/observations .
- Spring AOP cannot advice a private method of a Spring bean. The
mycode()
method should be in a bean and ideally public. ( Refer )
- The
Aspect
should also be a spring bean. This can be achieved by annotating the aspect with @Component
Remember to limit the scope : https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#writing-good-pointcuts
You may also go through this answer from @kriegaex to understand why an @annotation
has a global scope.
Update :
The code shared by OP also works with modifying a typo ( a space between the AnnotationName
and *
in the pointcut expression ) . The observations shared earlier holds good here as well.
@Component
@Aspect
public class SomeMethodAspect {
@Pointcut("execution(@so.qn69016852.anno.AnnotationName * so.qn69016852..*.*(..))")
private void someMethod() {}
@Around("someMethod() && @annotation(annotationName)")
public Object aroundSomeMethod(ProceedingJoinPoint pjp,AnnotationName annotationName) throws Throwable
{
System.out.println(annotationName.someBoolean());
System.out.println(annotationName.someString());
return pjp.proceed();
}
}