In a Servlet, you can get request scoped beans by:
If you're running in a dependency injection capable framework/container, it's even more easy:
Regardless of the scope, when you're actually inside the
However, when you're already inside the
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");
If you're running in a dependency injection capable framework/container, it's even more easy:
@Inject
private Bean bean;
Regardless of the scope, when you're actually inside the
FacesContext
, then 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:@SuppressWarnings("unchecked")
public static <T> T findBean(String beanName) {
FacesContext context = FacesContext.getCurrentInstance();
return (T) context.getApplication().evaluateExpressionGet(context, "#{" + beanName + "}", Object.class);
}
and can be used as follows:Bean bean = findBean("bean");
However, when you're already inside the
FacesContext
but not inside a dependency injection capable container, then using @ManagedProperty
is cleaner since it's more declarative.@ManagedProperty(value="#{bean}")
private Bean bean;
No hay comentarios:
Publicar un comentario