In my current setup, I need to access a method's annotation values AND the targeted class itself (or to be more precise, parts of it).
Here is what I am doing at the moment:
@Around("@annotation(CustomAnnotation) && target(myInterface)")
public Object interruptIfEmptyExtensionOrNoConnectorFound(
ProceedingJoinPoint proceedingJoinPoint,
MyInterface myInterface) throws Throwable {
...
}
The annotation carries an integer value designating a parameter (position) to do some checks on & MyInterface contains further (non-static) validation information.
If I add the Annotation to this method signature, I get
java.lang.IllegalArgumentException: error at ::0 formal unbound in pointcut
once Spring tries to load the ApplicationContext. The same happens if I try to change parameter order in the advice and/or remove the "target()" entry from the pointcut. (This loading currently takes the form of a SpringJUnit4ClassRunner with having the aspect and the class implementing the Interface as beans in the application context file.
Of course, I can get the annotation's values with proceedingJoinPoint.getTarget().getClass().getDeclaredMethod(...).getAnnotations()
and some for-each-ing, but using this way adds 10-15 lines to an otherwise 6-line-long parameter validation method and feels ... wrong.
I thought something like presented here would be possible if the "target" class is also in the advice method signature, but seems I am wrong or missunderstand something there.
Below are the non-working attempts to get the annotation:
@Around("@annotation(CustomAnnotation) && target(myInterface)")
public Object interruptIfEmptyExtensionOrNoConnectorFound(
ProceedingJoinPoint proceedingJoinPoint,
CustomAnnotation customAnnotation,
MyInterface myInterface) throws Throwable {
...
}
@Around("@annotation(CustomAnnotation) && target(myInterface)")
public Object interruptIfEmptyExtensionOrNoConnectorFound(
ProceedingJoinPoint proceedingJoinPoint,
MyInterface myInterface,
CustomAnnotation customAnnotation,) throws Throwable {
...
}
And this is how I currently retrieve the annotation:
MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
Method method = methodSignature.getMethod();
if (method.getDeclaringClass().isInterface()) {
method = proceedingJoinPoint.getTarget().getClass().getDeclaredMethod(proceedingJoinPoint.getSignature().getName(), method.getParameterTypes());
}
CustomAnnotation customAnnotation = null;
for (Annotation annotation : method.getAnnotations()) {
if (annotation.annotationType().equals(RequiresConnector.class)) {
customAnnotation = (CustomAnnotation) annotation;
}
}
return customAnnotation;