注释参数的Spring AOP切入点

时间:2012-04-20 13:22:10

标签: spring aop spring-aop pointcut

说我有这样的方法:

public void method(@CustomAnnotation("value") String argument)

是否有切入点表达式可以选择带有@CustomAnnotation注释参数的所有方法?如果是这样,我可以通过“价值”参数获取访问权限吗?

5 个答案:

答案 0 :(得分:16)

选择你的论点:

@Before("execution(* *(@CustomAnnotation (*)))")
public void advice() {
System.out.println("hello");
}

参考:http://forum.springsource.org/archive/index.php/t-61308.html

获取注释参数:

MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Annotation[][] methodAnnotations = method.getParameterAnnotations();

将为您提供可以迭代的注释,并使用instanceof查找绑定注释。我知道那是hacky但是afaik这是目前支持的唯一方式。

答案 1 :(得分:3)

只需完成最后一个答案:

@CustomAnnotation

将匹配一个方法,其中方法的参数之一(其中之一)用 service.doJob(@CustomAnnotation Pojo arg0, String arg1); 进行注释,例如:

@Before(value="execution(* *(@CustomAnnotation *, ..)) && args(input, ..)")
public void inspect(JoinPoint jp, Object input) {
            LOGGER.info(">>> inspecting "+input+" on "+jp.getTarget()+", "+jp.getSignature());
    }

相反
@CustomAnnotation

将与其中参数其中一个带有注释 service.doJob(AnnotatedPojo arg0, String arg1); 的方法匹配,例如:

@CustomAnnotation
public class AnnotatedPojo {
}

其中的pojo声明如下:

@CustomAnnotation (*)

所有区别都在于切入点声明中的@CustomAnnotation *const a = 1; const b = 2; const c = 'hello' function myfunction({a,b,c}){ console.log(c) } myfunction({c}) function wrapper({params}){}

答案 2 :(得分:2)

要匹配 1..N 个带注释的参数无论其位置如何使用

@Before("execution(* *(@CustomAnnotation (*), ..)) || " +
        "execution(* *(.., @CustomAnnotation (*), ..)) || " +                         
        "execution(* *(.., @CustomAnnotation (*)))")
public void advice(int arg1, @CustomAnnotation("val") Object arg2) { ... }

答案 3 :(得分:1)

如果你在方法中有多个参数,你应该使用两个点来表示任意数量的参数(零或更多)

@Before("execution(* *(@CustomAnnotation (*), ..))")
public void advice() {
    System.out.println("hello");
}

答案 4 :(得分:0)

来自Spring Docs:

@Before("@annotation(myAnnotation)")
public void audit(Auditable myAnnotation) {
  AuditCode code = auditable.value();
  // ...
}

对我来说效果很好,无需操纵方法签名。

注意:如果您使用的是命名切入点,因为切入点名称可能会重载,您必须提供匹配(参数名称和顺序)签名。

@Before("goodAdvise(myAnnotation)")
public void audit(Auditable myAnnotation) {
  String value = auditable.value();
  // ...
}

@Pointcut("@annotation(myAnnotation)")
public void goodAdvise(Auditable myAnnotation) { 
  //empty
}
相关问题