how to access custom annotation values in spring aspect

一曲冷凌霜 提交于 2021-02-11 07:35:41

问题


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.


回答1:


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);
    }
}



回答2:


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.




回答3:


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();
    }
}


来源:https://stackoverflow.com/questions/31189098/how-to-access-custom-annotation-values-in-spring-aspect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!