Search code examples
jsfjsf-2cdiinterceptormanaged-bean

Interceptors don't work with JSF managed beans?


I am decide to try interceptors My first interceptor binding annotation is

@Inherited
@InterceptorBinding
@Target({TYPE})
@Retention(RUNTIME)
public @interface WithLog {
  // No parameters required  
}

And interceptor class is

@Interceptor
@WithLog
public class LogInterceptor {

  @AroundInvoke
  private Object logMethod(InvocationContext context) throws Exception {
    System.out.println("Method " + context.getMethod().getName() + 
        " of class " + context.getTarget().getClass().getName() + " was called.");
    return context.proceed();
  }

  @PostConstruct
  private void construct(InvocationContext context) {
    System.out.println("@Postconstruct of " + 
        context.getMethod().getDeclaringClass().getName() + " started.");
  }
}

So, I want to add simple logging for JSF managed bean:

@ManagedBean(name = "departmentRootMB")
@ViewScoped
@WithLog
public class DepartmentRootMB implements Serializable {

  long serialVersionUID = 0L;
// . . . properties, methods

}

I read, that to enable interceptors I need to create beans.xml. I created one in the WEB-INF directory:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       bean-discovery-mode="annotated">
    <interceptors>
        <class>ru.edu.pgtk.weducation.interceptors.LogInterceptor</class>
    </interceptors>
</beans>

I rebuild project and no effect. Where is the mistake? What I did wrong? I use glassfish 4.1 with it standard components (WELD, EclipseLink, JSF 2.2.7)

Thanks for your time and best regards.


Solution

  • Interceptors don't work with JSF managed beans?

    Correct.

    Replace JSF bean management facility by CDI bean management facility.

    In other words, replace @ManagedBean and friends by @Named and friends. The JSF bean management facility is on the schedule to be deprecated in favor of CDI in a future Java EE version anyway. This is a good opportunity to migrate now you can.

    See also: