开发者

JSF2 ApplicationScope bean instantiation time?

开发者 https://www.devze.com 2023-03-26 14:14 出处:网络
It seems to me, that @ApplicationScoped beans are initiated only the first time they are accessed in a page using EL.

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

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

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

How else could I 开发者_StackOverflowtrigger the instantiation of the application scoped bean before an XHTML page has been loaded?


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

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

    // ...

}

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

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);
// ...

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 will auto-create it before injecting in the parent bean. It's available in all methods beyond @PostConstruct.

0

精彩评论

暂无评论...
验证码 换一张
取 消