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 楼答案
您没有解释为什么需要使用实现
ActionListener
接口的bean,而不是在UIComponent中使用方法限定符作为actionListener
属性正如您似乎已经尝试过的那样,使
CancelListener
成为CDIBean并不足以正确实例化它:LoginBean将为null但是,使用
binding
属性将强制JSF动态实例化bean,这将使技巧:如上所述,实现
ActionListener
的类也必须是CDIBean:另请参见:
How does the 'binding' attribute work in JSF? When and how should it be used?