拦截器在JSF管理的bean中不起作用?

3

我决定尝试使用 拦截器,我的第一个拦截器绑定注解是:

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

拦截器类是:
@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.");
  }
}

所以,我想为JSF托管的Bean添加简单的日志记录:

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

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

}

我看到,要启用拦截器,需要创建beans.xml文件。我在WEB-INF目录下创建了该文件:

<?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>

我重建了项目但没有生效。哪里出错了?我做错了什么?我使用的是glassfish 4.1和它的标准组件(WELD,EclipseLink,JSF 2.2.7)。

感谢您的时间和最好的祝愿。

1个回答

1

拦截器不能与JSF托管的bean一起使用吗?

正确。

用CDI bean管理设施替换JSF bean管理设施。

换句话说,用@Named和朋友们替换@ManagedBean和朋友们。 JSF bean管理设施计划在未来的Java EE版本中被弃用,而改用CDI。 现在是迁移的好机会。

另请参见:


我尝试将@ManagedBean替换为@Named,但是@ViewScoped不起作用,并且所有使用@Named注释的bean(我认为)都是请求范围。如何解决这个问题?有趣的是,在使用相同IDE和Maven等创建的其他项目中,没有这样的行为。这是什么情况? - gooamoko
如前所述,您还需要替换“friends”。换句话说,除其他外,还包括相关的范围注释。请使用CDI的@ViewScoped而不是JSF的注释。另请参见https://dev59.com/jWIj5IYBdhLWcg3wcEyI。 - BalusC
好的,我想我明白了我的错误。谢谢你的帖子。 - gooamoko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接