Java EE拦截器和@ViewScoped bean [英] Java EE Interceptors and @ViewScoped bean

查看:155
本文介绍了Java EE拦截器和@ViewScoped bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JBoss 7.1构建Java EE应用程序。

I'm building a Java EE application using JBoss 7.1.

为了对用户操作进行全面审核,我计划使用Interceptor来实现记录我的bean方法的每次调用。

In order to get a full audit of the user actions, I'm planing to use Interceptors to log every invocation of my beans' methods.

为此,我有以下招标:

@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();
    }
}

到目前为止,此工作正常。如果我使用这个拦截器绑定一个类,我会得到一些日志记录。但是,当我想要定位我的bean类时,它会变得更加棘手。

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

如果我有一个@RequestScoped类型的bean并将它绑定到我的拦截器就可以了。但是,如果我有一个@ViewScoped类型的bean,那么它不会

我查找了@ViewScoped的定义,我发现:

I looked up the definition of @ViewScoped and I found:

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

我觉得问题在于这个注释没有目标类型METHOD 并且它阻止我的拦截器拦截对类方法的调用。

I have the feeling that the problem lies in the fact that this annotation doesn't have the target type METHOD and that it prevents my interceptor to intercept calls to the class methods.

以前是否有人遇到过相同的问题?有人知道是否可以扩展bean的范围,以便在不改变@ViewScoped的性质的情况下拦截其方法?

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

推荐答案

这是因为拦截器无法访问@ManagedBean。 @ViewScope不是CDI的一部分,它带有JSF bean。

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

为了使它工作,最可靠的方法是使用@ViewScoped和CDI提供它的扩展。你的选择包括MyFaces CODI和Seam 3(例如)。

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

我已经通过安装 MyFaces CODI 并使用以下带有这些导入的注释:

I have got it working (the same way you describe it) by installing MyFaces CODI and using the following annotations with these imports:

import javax.faces.bean.ViewScoped;
import javax.inject.Named;

@Named
@ViewScoped
@Interceptors({ MyInterceptor.class})

这篇关于Java EE拦截器和@ViewScoped bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆