如何一次匹配类型OR方法注释

时间:2018-11-21 11:31:06

标签: aop guice interceptor

我想拥有一个Guice拦截器,该拦截器拦截对带注释的类或带注释的方法的调用。我希望能够将两者结合起来。用具有不同属性的方法注释覆盖类注释。

我的工作方式如下:

// Intercept all METHODS annotated with @MyAnnotation
bindInterceptor(
    Matchers.any(),
    Matchers.annotatedWith(company.MyAnnotation),
    new TracingInterceptor());

// Intercept all methods in CLASSES annotated with @MyAnnotation
bindInterceptor(
    Matchers.annotatedWith(company.MyAnnotation),
    Matchers.any(),
    new TracingInterceptor());

但是,当我注释这样的课程时:

@MyAnnotation    
class MyClass {
    @MyAnnotation
    public void myMethod() {}
}

拦截器被调用两次,这很糟糕!

有什么方法可以避免两次触发拦截器,但是行为相同?

1 个答案:

答案 0 :(得分:0)

您可以通过使绑定器互斥来实现此目的,如下所示:

// Intercept all METHODS annotated with @MyAnnotation in classes not annotated with @MyAnnotation
bindInterceptor(
    Matchers.not(Matchers.annotatedWith(company.MyAnnotation)),
    Matchers.annotatedWith(company.MyAnnotation),
    new TracingInterceptor());

// Intercept all methods not annotated with @MyAnnotation in CLASSES annotated with @MyAnnotation
bindInterceptor(
    Matchers.annotatedWith(company.MyAnnotation),
    Matchers.not(Matchers.annotatedWith(company.MyAnnotation)),
    new TracingInterceptor());

// Intercept all METHODS not annotated with @MyAnnotation in CLASSES annotated with @MyAnnotation
bindInterceptor(
    Matchers.annotatedWith(company.MyAnnotation),
    Matchers.annotatedWith(company.MyAnnotation),
    new TracingInterceptor());