Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何为advice方法提供切入点绑定的注释?_Java_Spring_Spring Aop - Fatal编程技术网

Java 如何为advice方法提供切入点绑定的注释?

Java 如何为advice方法提供切入点绑定的注释?,java,spring,spring-aop,Java,Spring,Spring Aop,所以我已经为特定注释的所有方法和所有类定义了切入点。。。我要做的是检索每个方法调用的注释值。这是我到目前为止所拥有的 @Aspect public class MyAspect { @Pointcut("execution(* my.stuff..*(..))") private void allMethods(){} @Pointcut("within(@my.stuff.MyAnnotation*)") private void myAnnotations

所以我已经为特定注释的所有方法和所有类定义了切入点。。。我要做的是检索每个方法调用的注释值。这是我到目前为止所拥有的

@Aspect
public class MyAspect {

    @Pointcut("execution(* my.stuff..*(..))")
    private void allMethods(){}

    @Pointcut("within(@my.stuff.MyAnnotation*)")
    private void myAnnotations(){}

    @Pointcut("allMethods() && myAnnotations()")
    private void myAnnotatedClassMethods(){}

    @Before("myAnnotatedClassMethods()")
    private void beforeMyAnnotatedClassMethods(){
        System.out.println("my annotated class method detected.");
        // I'd like to be able to access my class level annotation's value here.

    }

}

是的,您可以让SpringAOP提供注释目标对象类的注释值

您必须使用并在
@Pointcut
方法中传播参数

比如说

@Pointcut("execution(* my.stuff..*(..))")
private void allMethods() {
}

@Pointcut("@within(myAnnotation)")
private void myAnnotations(MyAnnotation myAnnotation) {
}

@Pointcut("allMethods() && myAnnotations(myAnnotation)")
private void myAnnotatedClassMethods(MyAnnotation myAnnotation) {
}

@Before("myAnnotatedClassMethods(myAnnotation)")
private void beforeMyAnnotatedClassMethods(MyAnnotation myAnnotation){
    System.out.println("my annotated class method detected: " + myAnnotation);
}
Spring从
myAnnotations
切入点开始,将把
@中给出的名称与方法参数匹配,并使用该参数确定注释类型。然后通过
myAnnotatedClassMethods
切入点将其传播到
beforeMynotatedClassMethods
建议

Spring AOP堆栈将在调用
@before
方法之前查找注释值,并将其作为参数传递


如果您不喜欢上面的解决方案,另一种选择是在advice方法中提供一个参数。您可以使用它解析
目标
实例,并使用该值获取类注释。比如说,

@Before("myAnnotatedClassMethods()")
private void beforeMyAnnotatedClassMethods(JoinPoint joinPoint) {
    System.out.println("my annotated class method detected: " + joinPoint.getTarget().getClass().getAnnotation(MyAnnotation.class));
}
如果目标被其他代理进一步包装,我不确定这将如何表现。注释可能“隐藏”在代理类后面。小心使用它