6

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?

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
alfonx
  • 6,936
  • 2
  • 49
  • 58

1 Answers1

9

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.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555