OmniFaces中的getBackingBean()

时间:2013-04-26 12:44:58

标签: jsf omnifaces

我可能对OmniFaces太盲目和太新了,并且在API中找不到基本方法来检索支持bean实例。如果有方法,哪里可以找到这样的方法?像这样:

public static Object getBackingBean(String name) {
    FacesContext context = FacesContext.getCurrentInstance();
    Application app = context.getApplication();
    ValueExpression expression = app.getExpressionFactory()
      .createValueExpression(context.getELContext(), String.format("#{%s}", name), Object.class);
    return expression.getValue(context.getELContext());
}

或带有泛型的更动态版本:

public static <T> T getBackingBean(String name) {
    FacesContext context = FacesContext.getCurrentInstance();
    Application app = context.getApplication();
    ValueExpression expression = app.getExpressionFactory()
      .createValueExpression(context.getELContext(), String.format("#{%s}", name), Object.class);
    return (T) expression.getValue(context.getELContext());
}

1 个答案:

答案 0 :(得分:2)

我们有一个类似的方法,但它可以评估(并获得)任何类型的表达式,而不仅仅是简化的根表达式。

这是Faces.evaluateExpressionGet

您可以按如下方式使用它:

MyBean myBean = Faces.evaluateExpressionGet("#{myBean}");

MyBean例如定义如下:

@ViewScoped
@ManagedBean
public class MyBean {
    // ...
}