如何将Spring bean注入JSF转换器

时间:2012-04-19 13:43:17

标签: spring jsf primefaces

我需要将Spring bean注入JSF(Primefaces)转换器。我尝试使用EL解析器注入豆子。但是,转换器内的bean为null

我的JSF转换器:

public class DepartmentConverter implements Converter  {
    private DepartmentService departmentService;
    //getter setter for this property

    @Override
    public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
        //codes
    }

    @Override
    public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
        //Codes
    }
}

faces-config.xml

<converter>
    <converter-id>DepartmentConverter</converter-id>
    <converter-class>com.studinfo.jsf.converter.DepartmentConverter</converter-class>
    <property>
        <property-name>departmentService</property-name>
        <property-class>com.studinfo.services.DepartmentService</property-class>
        <default-value>#{DepartmentService}</default-value>
    </property>
</converter>

EL解析器:

<application>
    <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>

当我调试代码时,departmentService属性为null。我可以用同样的方式访问托管JSF bean中的Spring bean。

1 个答案:

答案 0 :(得分:20)

直到JSF 2.3,转换器才是注入目标。将转换器改为JSF或Spring托管bean。以下示例使其成为JSF托管bean:

@ManagedBean
@RequestScoped
public class DepartmentConverter implements Converter  {
    // ...
}

并将其用作#{departmentConverter}而不是DepartmentConverter

E.g。

<h:inputSome ... converter="#{departmentConverter}" />

<h:someComponent>
    <f:converter binding="#{departmentConverter}" />
</h:someComponent>

不要忘记从<converter>移除faces-config.xml(如果您使用@FacesConverter注释,那么它本身就已经没有了,但是除此之外)。