Injecting a managedBean in a converter [duplicate]

牧云@^-^@ 提交于 2020-01-04 08:03:34

问题


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


回答1:


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}"



回答2:


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.



来源:https://stackoverflow.com/questions/13101081/injecting-a-managedbean-in-a-converter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!