In a Servlet, you can get request scoped beans by:
Bean bean = (Bean) request.getAttribute("beanName");
and session scoped beans by:
Bean bean = (Bean) request.getSession().getAttribute("beanName);
and application scoped beans by:
Bean bean = (Bean) getServletContext().getAttribute("beanName");
Regardless of the scope, when you're inside the FacesContext
, the normal JSF2 way is using Application#evaluateExpressionGet()
:
FacesContext context = FacesContext.getCurrentInstance();
Bean bean = (Bean) context.getApplication().evaluateExpressionGet(context, "#{beanName}", Bean.class);
which can be convenienced as follows:
public static <T> T findBean(String beanName, Class<T> beanClass) {
FacesContext context = FacesContext.getCurrentInstance();
return beanClass.cast(context.getApplication().evaluateExpressionGet(context, "#{" + beanName + "}", beanClass);
}
and can be used as follows:
Bean bean = findBean("bean", Bean.class);
If you're running in a dependency injection capable framework/container, it's even more easy:
@Inject
private Bean bean;