1

I am trying to access the custom annotation values from jointCut. But I couldn't find a way.

My sample code :

@ComponentValidation(input1="input1", typeOfRule="validation", logger=Log.EXCEPTION)
public boolean validator(Map<String,String> mapStr) {
    //blah blah
}

Trying to access @Aspect class.

But, i didnt see any scope to access values.

Way i am trying to access is below code

CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature(); 
String[] names = codeSignature.getParameterNames();
MethodSignature methodSignature = (MethodSignature) joinPoint.getStaticPart().getSignature();
Annotation[][] annotations = methodSignature.getMethod().getParameterAnnotations();
Object[] values = joinPoint.getArgs();

i didnt see any value returns input = input1. how to achieve this.

kriegaex
  • 63,017
  • 15
  • 111
  • 202
pradeep cs
  • 513
  • 4
  • 9
  • 34
  • Can you provide all the code including the entire custom validation – Mudassar Jul 02 '15 at 17:15
  • Hi, I am also in my learning phase of custom annotation with aspectj. Can you please provide me a demo of how to use custom annotation ? I am new with spring aspectj. Any help will be appreciate. Thanks in advance. – Jimmy Jul 06 '15 at 18:52

3 Answers3

2

While the answer by Jama Asatillayev is correct from a plain Java perspective, it involves reflection.

But the question was specifically about Spring AOP or AspectJ, and there is a much simpler and more canonical way to bind matched annotations to aspect advice parameters with AspectJ syntax - without any reflection, BTW.

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

import my.package.ComponentValidation;

@Aspect
public class MyAspect {
    @Before("@annotation(validation)")
    public void myAdvice(JoinPoint thisJoinPoint, ComponentValidation validation) {
        System.out.println(thisJoinPoint + " -> " + validation);
    }
}
kriegaex
  • 63,017
  • 15
  • 111
  • 202
0

For getting values, use below:

ComponentValidation validation = methodSignature.getMethod().getAnnotation(ComponentValidation.class);

you can call validation.getInput1(), assuming you have this method in ComponentValidation custom annotation.

Jama A.
  • 15,680
  • 10
  • 55
  • 88
0

For example if you have defined a method in Annotation interface like below :

@Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface AspectParameter {
    String passArgument() default "";
}

then you can access the class and the method values in the aspect like below :

@Slf4j
@Aspect
@Component
public class ParameterAspect {

    @Before("@annotation(AspectParameter)")
    public void validateInternalService(JoinPoint joinPoint, AspectParameter aspectParameter) throws Throwable {    
        String customParameter = aspectParameter.passArgument();
    }
}
denzal
  • 1,225
  • 13
  • 20