How do I force an application-scoped bean to instantiate at application startup?

My first thought was to use an old style ServletContextListener contextInitialized() method and from there use an ELResolver to manually request the instance of my managed bean (thus forcing the initialization to happen). Unfortunately, I can’t use an ELResolver to trigger the initialization at this stage because the ELResolver needs a FacesContext and the FacesContext only exists during the lifespan of a request.

It doesn’t need to be that complicated. Just instantiate the bean and put it in the application scope with the same managed bean name as key. JSF will just reuse the bean when already present in the scope. With JSF on top of Servlet API, the ServletContext represents the application scope (as HttpSession represents the session scope and HttpServletRequest represents the request scope, each with setAttribute() and getAttribute() methods).

This should do,

public void contextInitialized(ServletContextEvent event) {
    event.getServletContext().setAttribute("bean", new Bean());
}

where "bean" should be the same as the <managed-bean-name> of the application scoped bean in faces-config.xml.


Just for the record, on JSF 2.x all you need to do is to add eager=true to @ManagedBean on an @ApplicationScoped bean.

@ManagedBean(eager=true)
@ApplicationScoped
public class Bean {
    // ...
}

It will then be auto-instantiated at application startup.

Or, when you’re managing backing beans by CDI @Named, then grab OmniFaces @Eager:

@Named
@Eager
@ApplicationScoped
public class Bean {
    // ...
}

Leave a Comment