Inject managed-bean property into custom converter

2019-02-21 18:26发布

问题:

How can I inject a property of a managed-bean into a custom converter?

For instance, a generic List so that I can extract my object from the list inside the converter?

回答1:

In several case, when you need to inject a bean such as ManagedBean, EJB, etc. into a Converter or a Validator, you can try annotating your Converter or Validator as a ManagedBean. For example, you can try this:

@ManagedBean
@RequestScoped
public class MyConverter implements Converter {
    @EJB
    private MrEJBBean mrEJBBean;
    @ManagedProperty(value="#{mrsManagedBean}")        
    private MrsManagedBean mrsManagedBean;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {        
        // Convert to object
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        // Convert to string
    }

}

You can take a look at this for an example on Validator.