Search code examples
jsfjsf-2cdiinterceptormanaged-bean

Is it possible intercept a method from @ManagedBean? If not, there alternatives?


I'm new to JSF-2 and CDI (I'm from Spring world).

I want to intercept a method from @ManagedBean but my Interceptor class is never called. Is it possible to do?

LogInterceptor.java

@Interceptor
public class LogInterceptor {

    @AroundInvoke
    public Object log(InvocationContext ctx) throws Exception {
        System.out.println("begin method interceptor");
        Object methodReturn = ctx.proceed();
        System.out.println("end method interceptor");

        return methodReturn;
    }   
}



RoleMB

@ManagedBean
@ViewScoped
public class RoleMB extends BaseMB {

    @Interceptors(LogInterceptor.class)
    public void preEditRole(Role role) {
        ...
    }
}



beans.xml

<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">

    <interceptors>
        <class>br.com.preventsenior.services.log.LogInterceptor</class>
    </interceptors>

</beans>



The log(InvocationContext ctx) is never called.


Solution

  • Java EE interceptors work only on CDI managed beans and EJBs, not on JSF managed beans.

    So, you've basically 2 options:

    1. Change JSF bean management annotations by CDI bean management annotations (@Named et.al.)

    2. Intercept on an EJB method instead which is in turn invoked by JSF managed bean. In a sane Java EE application, the real business logic belongs in EJBs anyway.