How do I access EJB bean when inside a custom Conv

2020-08-01 07:26发布

问题:

This converter is called from my JSF. I already register it inside faces-config.xml

public class ProjectConverter implements Converter{

    @EJB
    DocumentSBean sBean;

    @ManagedProperty(value="#{logging}")
    private Logging log;    

    public ProjectConverter(){
    }

    public Object getAsObject(FacesContext context, UIComponent component, String value) 
    {
        if(value.trim().equals("")){
            return null;
        }
        return sBean.getProjectById(value);

    }

    public String getAsString(FacesContext context, UIComponent component, Object value) 
    {
        if(value == null){
            return null;
        }
        return String.valueOf(((Project) value).getId());
    }
}

I ran into java.lang.NullPointerException, when I am in getAsObject(), the primary reason is because my Session Bean sBean is null. I dont know how to fix this, I need to access to my Session bean so that I can query from my database

回答1:

As BalusC said, injection only works in managed beans. You can however declare your converter as a managed bean in your faces-config

<managed-bean>
   <managed-bean-name>myConverter</managed-bean-name>
   <managed-bean-class>com.example.MyConverter</managed-bean-class>
   <managed-bean-scope>request</managed-bean-scope>
</managed-bean>

And later reference it in a jsf component with an el expression:

<h:outputText value="#{myBean.value}" converter="#{myConverter}" />