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 とのインターセプターの使用
インターセプターバインディングタイプを定義します。
@InterceptorBinding @Retention(RUNTIME) @Target({TYPE, METHOD}) public @interface Secure {}インターセプター実装をマーク付けします。
@Secure @Interceptor public class SecurityInterceptor { @AroundInvoke public Object aroundInvoke(InvocationContext ctx) throws Exception { // enforce security ... return ctx.proceed(); } }ビジネスコードでインターセプターを使用します。
@Secure public class AccountManager { public boolean transfer(Account a, Account b) { ... } }META-INF/beans.xmlまたはWEB-INF/beans.xmlファイルに追加して、デプロイメントでインターセプターを有効にします。<beans> <interceptors> <class>com.acme.SecurityInterceptor</class> <class>com.acme.TransactionInterceptor</class> </interceptors> </beans>インターセプターは、リストされた順序で適用されます。
結果:
CDI は、インターセプターコードを簡素化し、ビジネスコードへの適用を容易にします。