Injecting a managedBean in a converter [duplicate]

2019-07-21 08:00发布

I'm trying to write a converter for my selectonemenu list so the list that i want to display can be retrieved from a managedBean's getter getDatasetList() . My managedBean is viewScoped.

here's the code of the converter:

@FacesConverter(value = "datasetConverter")
public class DatasetConverter implements Converter{

@ManagedProperty(value="#{projectCampaignManagementMB}")
private ProjectCampaignManagementMB campaignManagementMB;

@Override
public Object getAsObject(FacesContext context, UIComponent component,
        String value) {

     List <DataSet>  datasetList=campaignManagementMB.getDatasetList();

     DataSet dataSet;
     String dataSetName;
     if (datasetList!=null){
            for(int i=0 ;i<datasetList.size();i++)
            {   
                dataSet=datasetList.get(i);
                dataSetName=dataSet.getName();

            if  (dataSetName.equals(value))
                return dataSet;
            System.out.println("getasobject dataset"+dataSet.getName());
            }
     }
            return null;
}

@Override
public String getAsString(FacesContext context, UIComponent component,
        Object value) {

 if (value==null) return ""; 
    System.out.println("getastring dataset"+((DataSet) value).getName());
 return ((DataSet) value).getName();
}

But i'm getting a java.lang.NullPointerException on this line

  List <DataSet>  datasetList=campaignManagementMB.getDatasetList();

So the injected managedBean is Null,

i tried something that has no sense but it works ,but i want something correct . i used this

@ManagedProperty(value="#{projectCampaignManagementMB}")
private ProjectCampaignManagementMB campaignManagementMB =
    new ProjectCampaignManagementMB();

instead of

@ManagedProperty(value="#{projectCampaignManagementMB}")
private ProjectCampaignManagementMB campaignManagementMB

Any help will be appreciated

2条回答
2楼-- · 2019-07-21 08:37

When you want to use managed properties inside your convertor make your convertor a managed bean, like this

@ManagedBean
@SessionScoped
public class DatasetConverter implements Converter{

Than to use it as convertor in your xhtml page just use binding

like this

<h:inputText converter="#{datasetConverter}"
查看更多
在下西门庆
3楼-- · 2019-07-21 08:50

I had a similar problem some time ago and I remember that @Inject did not work for me with the converter. What helped me was directly looking up the bean with its JNDI name. Something along this lines:

Context context = new InitialContext();  
BeanClass bean = context.lookup("yours bean jndi");

If you are using JBoss you can see the beans JNDI on the server startup.

查看更多
登录 后发表回答