dontnetnewbie
dontnetnewbie

Reputation: 159

EL Expression in JSF 2.2

I am using JSF 2.2 and I need to get an instance of the managed bean using EL Expression. I am using the below code which creates an instance of the managed bean if its not already created. If the bean is already created and is in memory (any scoped variable be it in session, request, ..), it returns that instance of the managed bean with out creating a new one. My requirement is, if the bean is not already created, then it should return null and not create a new instance. If it's is already created , then it should return that instance. But the below code, ends up creating one if it doesn't exists. Hope I am clear.

public static MyManagedBean getMyManagedBean () {

MyManagedBean  bean = (MyManagedBean ) getFacesContext().getApplication().getExpressionFactory().createValueExpression(getELContext(),
        "#{MyManagedBean}",
        MyManagedBean .class).getValue(FacesContext.getCurrentInstance().getELContext());
return bean;

}

Upvotes: 1

Views: 291

Answers (1)

Michele Mariotti
Michele Mariotti

Reputation: 7469

This is the simple (but verbose) version:

public static <T> T resolveBean(String name)
{
    FacesContext context = FacesContext.getCurrentInstance();
    ExternalContext externalContext = context.getExternalContext();

    Map<String, Object> requestMap = externalContext.getRequestMap();
    Object requestObject = requestMap.get(name);
    if(requestObject != null)
    {
        return (T) requestObject;
    }

    Map<String, Object> viewMap = context.getViewRoot().getViewMap();
    Object viewObject = viewMap.get(name);
    if(viewObject != null)
    {
        return (T) viewObject;
    }

    Map<String, Object> sessionMap = externalContext.getSessionMap();
    Object sessionObject = sessionMap.get(name);
    if(sessionObject != null)
    {
        return (T) sessionObject;
    }

    Map<String, Object> applicationMap = externalContext.getApplicationMap();
    Object applicationObject = applicationMap.get(name);
    if(applicationObject != null)
    {
        return (T) applicationObject;
    }

    BeanManager beanManager = CDI.current().getBeanManager();
    Bean<T> bean = (Bean<T>) beanManager.resolve(beanManager.getBeans(name));
    if(bean != null)
    {
        Context cdiContext = beanManager.getContext(bean.getScope());
        T instance = cdiContext.get(bean);
        if(instance != null)
        {
            return instance;
        }
    }

    return null;
}

Upvotes: 3

Related Questions