Search code examples
javajakarta-eecdiinterceptor

Annotation-based interceptors on EJBs


Is it possible to declare interceptors on EJBs using interceptor-binding-able annotations, like we do on CDI beans?

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@InterceptorBinding
public @interface MyInterceptor {
}

@Stateless
@Remote(MyService.class)
public MyServiceImpl implements MyService {

     @Override
     @MyInterceptor
     public String myBusinessMethod() {
          return "";
     }

}

Solution

  • Yes, it's possible. You can treat the EJBs almost like any other CDI bean. You need to either activate the interceptors in the beans.xml or add an @Interceptor binding. See the weld documentation for more information https://docs.jboss.org/weld/reference/1.0.0/en-US/html/interceptors.html

    The standard EJB annotations are implemented like this as well, as can be seen in the src or the above mentioned documenation link.