将CDI SessionScoped bean注入JSF ValueChangeListener

时间:2016-04-11 20:00:02

标签: jsf cdi valuechangelistener

我正在尝试使用javax.faces.event.ValueChangeListenerh:selectOneMenu这样的

<h:selectOneMenu value="#{localeBean.languageCode}" onchange="submit()">
    <f:selectItem itemLabel="English" itemValue="en" />
    <f:selectItem itemLabel="German" itemValue="de" />
    <f:valueChangeListener  type="org.bitbucket.paulstat.jsf.event.ExampleValueChangeListener" />
</h:selectOneMenu>

这是听众

import javax.faces.event.AbortProcessingException;
import javax.faces.event.ValueChangeEvent;
import javax.faces.event.ValueChangeListener;
import javax.inject.Inject;

import org.bitbucket.paulstat.jsf.localisation.LocaleBean;

public class ExampleValueChangeListener implements ValueChangeListener {

    @Inject
    private LocaleBean localeBean;

    @Override
    public void processValueChange(ValueChangeEvent event) throws AbortProcessingException {
        localeBean.setLanguageCode(event.getNewValue().toString());
        localeBean.switchLocale();
    }

}

LocaleBean

import java.io.Serializable;
import java.util.Locale;

import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;

@Named
@SessionScoped
public class LocaleBean implements Serializable {

    private String languageCode;

    public void switchLocale() {
        FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale(languageCode));
    }

    public void setLanguageCode(String languageCode) {
        this.languageCode = languageCode;
    }

    public String getLanguageCode() {
        return languageCode;
    }

}

LocaleBean似乎没有被注入值更改侦听器并且为null。我们可以将SessionScoped CDI bean与JSF ValueChangeListeners混合使用吗?

1 个答案:

答案 0 :(得分:1)

@Inject仅适用于CDI托管bean。您的ExampleValueChangeListener不是CDI托管bean。

制作一个。最简单的方法是在其上放置@Named注释,以便它可以在EL中使用。

@Named
public class ExampleValueChangeListener implements ValueChangeListener {
    // ...
}

通过binding而不是type引用它。

<f:valueChangeListener binding="#{exampleValueChangeListener}" />

另见: