9

I need to inject Spring beans into a JSF (Primefaces) converter. I tried to inject beans by using EL resolver. However, the beans are null inside the converters.

My JSF converter:

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 resolver:

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

When I debug my code, the departmentService property is null. I can access the Spring beans inside a managed JSF bean the same way.

Karl Richter
  • 6,271
  • 17
  • 57
  • 120
erencan
  • 3,640
  • 5
  • 28
  • 50

1 Answers1

21

Until JSF 2.3, converters are no injection targets. Make the converter a JSF or Spring managed bean instead. The below example makes it a JSF managed bean:

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

And use it as #{departmentConverter} instead of DepartmentConverter.

E.g.

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

or

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

Don't forget to remove the <converter> from faces-config.xml (which was at its own already unnecessary if you used the @FacesConverter annotation, but that aside).

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452