Java EE Interceptors and @ViewScoped bean

I am building a Java EE application using JBoss 7.1.

To get a complete audit of user actions, I plan to use Interceptors to register every call to my beans methods.

For this, I have the following gain:

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

Then I define my interceptor class:

 @Logged @Interceptor public class UserActionInterceptor implements Serializable { private static final long serialVersionUID = 1L; private Logger log = LoggerFactory.getLogger(UserActionInterceptor.class); public UserActionInterceptor() { } @AroundInvoke public Object logMethodEntry(InvocationContext invocationContext) throws Exception { log.debug(invocationContext.getMethod().getName() + " invoked."); return invocationContext.proceed(); } } 

So far this is working fine. If I bind a class using this Interceptor, I get some entries. However, it gets harder when I want to target my beans classes.

If I have a bean like @RequestScoped and bind it to my interceptor, it works. However, if I have a bean of type @ViewScoped, then this is not .

I looked at the @ViewScoped definition and found:

 @Retention(value=RUNTIME) @Target(value=TYPE) @Inherited public @interface ViewScoped 

I have the feeling that the problem is that this annotation does not have the target METHOD type and that it does not allow the interceptor to intercept calls to class methods.

Has anyone had the same problem? Does anyone know if it is possible to extend the scope of a bean so that its methods can be intercepted without changing the nature of @ViewScoped?

+6
source share
2 answers

This is because the interceptor cannot access @ManagedBean. @ViewScope is not part of CDI and comes with JSF beans.

To make it work, the best way is to use @ViewScoped with CDI using one of the extensions that provides it. Your options include MyFaces CODI and Seam 3 (for example).

I have a job (just as you described it) by installing MyDaces CODI and using the following annotations with these imports:

 import javax.faces.bean.ViewScoped; import javax.inject.Named; @Named @ViewScoped @Interceptors({ MyInterceptor.class}) 
+3
source

or maybe you can try this nice theme http://www.verborgh.be/articles/2010/01/06/porting-the-viewscoped-jsf-annotation-to-cdi/ , Steven Verborgh explains how to use the extension CDI to create your own ViewScope.

0
source

Source: https://habr.com/ru/post/927464/


All Articles