有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JSF/CDI依赖项注入ActionListener

为什么CDI不在这个ActionListener中注入我的支持bean(会话范围)?loginBean实例始终为空。我的印象是CDI不管理侦听器实例:是吗

import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.inject.Inject;

public class CancelListener implements javax.faces.event.ActionListener {

    private LoginBean loginBean; 

    @Inject
    public void setLoginBean(LoginBean loginBean) {
        this.loginBean = loginBean;
    }

    @Override
    public void processAction( ActionEvent event ) throws AbortProcessingException {
        loginBean.setLogin( "" );
        loginBean.setPassword( "" );
    }

}

这里是我的LoginBean类的定义

import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.faces.event.ActionEvent;
import javax.inject.Named;


@Named
@SessionScoped 
public class LoginBean implements Serializable {

    private static final long serialVersionUID = -5433850275008415405L;

    private String login = "james@mi6.uk";
    private String password = "007";

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

我的监听器通过以下代码连接到按钮:

<h:commandButton value="Cancel" immediate="true">
    <f:actionListener type="mypackage.CancelListener" />
</h:commandButton>

我知道我可以直接在支持bean上使用方法(与actionListener标记属性连接),但我想了解如何使我的类与CDI兼容,以及在这种情况下如何强制注入。提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    您没有解释为什么需要使用实现ActionListener接口的bean,而不是在UIComponent中使用方法限定符作为actionListener属性

    正如您似乎已经尝试过的那样,使CancelListener成为CDIBean并不足以正确实例化它:LoginBean将为null

    但是,使用binding属性将强制JSF动态实例化bean,这将使技巧:

    <h:commandButton value="Cancel" immediate="true">
        <f:actionListener binding="#{cancelListener}" type="mypackage.CancelListener" />
    </h:commandButton>    
    

    如上所述,实现ActionListener的类也必须是CDIBean:

    @Named
    @SessionScoped
    public class CancelListener implements Serializable, javax.faces.event.ActionListener {
    
        @Inject
        private LoginBean loginBean;
    
        @Override
        public void processAction(ActionEvent event) throws AbortProcessingException {
            System.out.println(this.toString());
            System.out.println(loginBean.toString());
        }        
    }
    

    另请参见:

    How does the 'binding' attribute work in JSF? When and how should it be used?