1

我正在尝试从jointCut 访问自定义注释值。但我找不到办法。

我的示例代码:

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

试图访问@Aspect类。

但是,我没有看到任何访问值的范围。

我尝试访问的方式如下代码

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

我没有看到任何值返回 input = input1。如何实现这一目标。

4

3 回答 3

2

虽然Jama Asatillayev的回答从普通 Java 的角度来看是正确的,但它涉及到反射。

但是这个问题专门关于 Spring AOP 或 AspectJ,并且有一种更简单、更规范的方法可以使用 AspectJ 语法将匹配的注释绑定到方面建议参数 - 顺便说一句,没有任何反射。

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);
    }
}
于 2015-07-12T09:51:44.740 回答
0

要获取值,请使用以下内容:

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

您可以调用validation.getInput1(),假设您在ComponentValidation自定义注释中有此方法。

于 2015-07-02T18:15:26.830 回答
0

例如,如果您在 Annotation 接口中定义了一个方法,如下所示:

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

然后您可以在如下方面访问类和方法值:

@Slf4j
@Aspect
@Component
public class ParameterAspect {

    @Before("@annotation(AspectParameter)")
    public void validateInternalService(JoinPoint joinPoint, AspectParameter aspectParameter) throws Throwable {    
        String customParameter = aspectParameter.passArgument();
    }
}
于 2017-11-15T12:39:48.423 回答