Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF2 ApplicationScope bean instantiation time?

Tags:

java

jsf

jsf-2

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 trigger the instantiation of the application scoped bean before an XHTML page has been loaded?

like image 881
alfonx Avatar asked Aug 06 '11 13:08

alfonx


1 Answers

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.

like image 77
BalusC Avatar answered Sep 29 '22 03:09

BalusC