0

Interception with CDI works perfectly in @Named , but doesn't in @ManagedBean:

Logable.java

@InterceptorBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Logable {

}

LoggingInterceptor.java

@Logable
@Interceptor
public class LoggingInterceptor {
@AroundInvoke
    public Object log(InvocationContext ctx) throws Exception {
//log smth. with ctx.
}
}

WorkingBean.java

@Named
@Logable
public class WorkingBean implements Serializable {
 //works : methods will be logged
}

beans.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  <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>LoggingInterceptor</class>
</interceptors>

</beans>

ViewScopedBean.java

@Logable
@ManagedBean
public class ViewScopedBean implements Serializable {
 //doesn't work
}

I'm aware, that this kind of Interceptor is meant to work with WebBeans (and EJB), but i'm searching for solution for both worlds (described + JSF) with same Interceptor concept I need @ViewScoped @ManagedBean, thats why i cant get rid of @ManagedBean in favour of pure WebBeans

System: Mojarra 2.1.7 Primefaces 3.2

iga
  • 41
  • 1
  • 5

2 Answers2

1

As far as I understand, there isn't one. JSF doesn't have anything supporting interception.

LightGuard
  • 5,298
  • 19
  • 19
  • pretty unsatisfying... probably is [this](http://stackoverflow.com/questions/8709107/interceptor-in-jsf?rq=1) the unpretty way to go – iga Jun 29 '12 at 11:58
  • That is ugly! JSF was originally created before AOP was around. It simply wasn't anything that was thought of. Also now, you have CDI and EJB interceptors so there's no point. JSF 2.2 would allow you to do CDI interceptors. – LightGuard Jun 30 '12 at 15:01
1

JSF does not support the CDI interception like you have posted per se. A CDI interceptor will work for lifecycle methods like @PostConstruct

    @Inherited
    @InterceptorBinding
    @Retention(RUNTIME)
    @Target({TYPE})
    public @interface TypeLogger {

      @Nonbinding
      public LoggingLevel logLevel() default LoggingLevel.INFO;
    }

Here is how it would be used since it only binds to the @Target({TYPE})

    @ManagedBean
    @ViewScoped
    @TypeLogger
    public class Index implements Serializable {

       private static final long serialVersionUID = 3336392241545517919L;

       @PostConstruct
       private void init() {
         setup();
       }
    }
John Yeary
  • 1,112
  • 22
  • 45