是否有可能从@ManagedBean拦截一个方法?如果没有,有其他选择吗?

eth*_*b_0 2 jsf interceptor cdi jsf-2 managed-bean

我是JSF-2和CDI的新手(我来自Spring世界).

我想从@ManagedBean拦截一个方法,但我的Interceptor类永远不会被调用.有可能吗?

LogInterceptor.java

@Interceptor
public class LogInterceptor {

    @AroundInvoke
    public Object log(InvocationContext ctx) throws Exception {
        System.out.println("begin method interceptor");
        Object methodReturn = ctx.proceed();
        System.out.println("end method interceptor");

        return methodReturn;
    }   
}
Run Code Online (Sandbox Code Playgroud)



RoleMB

@ManagedBean
@ViewScoped
public class RoleMB extends BaseMB {

    @Interceptors(LogInterceptor.class)
    public void preEditRole(Role role) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)



beans.xml中

<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>br.com.preventsenior.services.log.LogInterceptor</class>
    </interceptors>

</beans>
Run Code Online (Sandbox Code Playgroud)



log(InvocationContext ctx)永远不会被调用.

Bal*_*usC 8

Java EE拦截器仅适用于CDI托管bean和EJB,而不适用于JSF托管bean.

所以,你基本上有两个选择:

  1. 通过CDI bean管理注释更改JSF bean管理注释(@Namedet.al.)

  2. 拦截EJB方法,而JSE托管bean又调用它.在一个理智的Java EE应用程序中,真正的业务逻辑无论如何都属于EJB.