Red Hat Training

A Red Hat training course is available for Red Hat JBoss Enterprise Application Platform

11.2.10.2. CDI とのインターセプターの使用

例11.19 CDI のないインターセプター

CDI がない場合、インターセプターには 2 つの問題があります。
  • Bean は、インターセプター実装を直接指定する必要があります。
  • アプリケーションの各 Bean は、インターセプターの完全なセットを適切な順序で指定する必要があります。この場合、アプリケーション全体でインターセプターを追加または削除するには時間がかかり、エラーが発生する傾向があります。
@Interceptors({
  SecurityInterceptor.class,
  TransactionInterceptor.class,
  LoggingInterceptor.class
})
@Stateful public class BusinessComponent {
  ...
}

手順11.7 CDI とのインターセプターの使用

  1. インターセプターバインディングタイプを定義します。

    @InterceptorBinding
    @Retention(RUNTIME)
    @Target({TYPE, METHOD})
    public @interface Secure {}
    
  2. インターセプター実装をマーク付けします。

    @Secure
    @Interceptor
    public class SecurityInterceptor {
      @AroundInvoke
      public Object aroundInvoke(InvocationContext ctx) throws Exception {
        // enforce security ...
        return ctx.proceed();
        }
    }
    
  3. ビジネスコードでインターセプターを使用します。

    @Secure
    public class AccountManager {
      public boolean transfer(Account a, Account b) {
        ...
      }
    }
    
  4. META-INF/beans.xml または WEB-INF/beans.xml ファイルに追加して、デプロイメントでインターセプターを有効にします。

    <beans>
      <interceptors>
        <class>com.acme.SecurityInterceptor</class>
        <class>com.acme.TransactionInterceptor</class>
      </interceptors>
    </beans>
    インターセプターは、リストされた順序で適用されます。

結果:

CDI は、インターセプターコードを簡素化し、ビジネスコードへの適用を容易にします。