JSF2 ApplicationScope bean实例化时间? [英] JSF2 ApplicationScope bean instantiation time?

查看:128
本文介绍了JSF2 ApplicationScope bean实例化时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来, @ApplicationScoped bean仅在第一次使用EL访问页面时启动。

It seems to me, that @ApplicationScoped beans are initiated only the first time they are accessed in a page using EL.

当我查询 ApplicationMap 时,是否会创建 @ApplicationScoped bean?

When I query the ApplicationMap, will the @ApplicationScoped bean be created?

ExternalContext ec = currentInstance.getExternalContext(); result =
    ec.getApplicationMap().get(beanName);

如何在加载XHTML页面之前触发应用程序作用域bean的实例化?

How else could I trigger the instantiation of the application scoped bean before an XHTML page has been loaded?

推荐答案

您可以在 eager = true http://download.oracle.com/javaee/6/api/javax/faces/bean/ManagedBean.html\"rel =nofollow noreferrer> @ManagedBean 声明。

You could use eager=true in the @ManagedBean declaration.

@ManagedBean(eager=true)
@ApplicationScoped
public class Config {

    // ...

}

这样bean将在webapp的启动时自动处理。

This way the bean will be autocreated on webapp's startup.

除此之外,你还可以使用 Application#evaluateExpressionGet() 以编程方式评估EL等自动crea如果有必要的话。另请参阅此答案上的示例。

Instead of that, you could also use Application#evaluateExpressionGet() to programmatically evaluate EL and so auto-create the bean if necessary. See also the example on this answer.

FacesContext context = FacesContext.getCurrentInstance();
Confic config = (Config) context.getApplication().evaluateExpressionGet(context, "#{config}", Config.class);
// ...

您也可以将其注入 @ManagedProperty 你需要它的bean。

You could also just inject it as a @ManagedProperty of the bean where you need it.

@ManagedBean
@RequestScoped
public class Register {

    @ManagedProperty("#{config}")
    private Config config;

    @PostConstruct
    public void init() {
        // ...
    }

    // ...
}

JSF将在注入父bean之前自动创建它。它可用于 @PostConstruct 之外的所有方法。

JSF will auto-create it before injecting in the parent bean. It's available in all methods beyond @PostConstruct.

这篇关于JSF2 ApplicationScope bean实例化时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆