@Interceptors和@InterceptorBinding + @Logged之间的区别?

时间:2016-05-25 04:32:39

标签: java intellij-idea annotations cdi interceptor

似乎有两种方法可以将拦截器绑定到目标类/方法:

  1. @Interceptors on target class/method
  2. Declare a interceptor binding type(aka, a custom annotation annotated with @InterceptorBinding itself, for example @Logged), and using it on target class/method
  3. 我在CDI环境中使用拦截器。我的问题是,如果我使用@Interceptors将拦截器绑定到我的目标方法,是否完全没有必要声明一个额外的interceptor binding type

    如果答案是,那么为什么IntelliJ IDEA经常抱怨我错误

      

    @Interceptor必须至少指定一个拦截器绑定

    当我没有在我的拦截器上注释interceptor binding type时?

    如果答案是,我已经使用@Interceptors(arrayOfMyInceptor)直接将我的拦截器绑定到目标类/方法,为什么要声明一个额外的interceptor binding type和在我的拦截器上使用它?


    我在网上搜索但是找不到这两种方法的差异,希望SO可以解决我的问题。

    感谢您的耐心等待。

1 个答案:

答案 0 :(得分:0)

注释@Interceptor和其他costum注释如@Logged应该在拦截器类上调用,例如

@Logged
@Interceptor
@Priority(Interceptor.Priority.APPLICATION)
public class LoggedInterceptor implements Serializable { ... }

必须在您要创建的注释上调用注释@InterceptorBinding,以使其明确,这有点像“拦截器限定符”。

@Inherited
@InterceptorBinding
@Retention(RUNTIME)
@Target({METHOD, TYPE})
public @interface Logged {
}

然后,您可以在(托管)bean或其方法上调用拦截器绑定注释。

@Logged
public String pay() {...}

@Logged
public void reset() {...}
  

请参阅java教程以获取更多帮助https://docs.oracle.com/javaee/7/tutorial/cdi-adv006.htm

修改

因为我误解了你的问题,这是我的编辑: 注释@Interceptors就像拦截器的集合。 通过将几个拦截器类(例如LoggedInterceptor@Logged)传递到应用的value注释的@Interceptors变量,可以调用所有这些拦截器绑定:

@Interceptors({LoggedInterceptor.class,
OtherInterceptor.class,.....})

因此,您需要至少一个@Interceptors

的拦截器绑定

所以你需要拦截器类本身的拦截器绑定而不是目标类,因为它已经在@Interceptors注释中提到了。

  

请参阅API文档https://docs.oracle.com/javaee/7/api/javax/interceptor/Interceptors.html