How can I initialize a Java FacesServlet
jakarta-ee, jsf, jsf-2
Solution
Use an eagerly initialized application scoped managed bean.
@ManagedBean(eager=true)
@ApplicationScoped
public class App {
@PostConstruct
public void startup() {
// ...
}
@PreDestroy
public void shutdown() {
// ...
}
}
(class and method names actually doesn't matter, it's free to your choice, it's all about the annotations)
This is guaranteed to be constructed after the startup of the `FacesServlet`, so the `FacesContext` will be available whenever necessary. This in contrary to the `ServletContextListener` as suggested by the other answer.
Problem
I need to run some code when the FacesServlet starts, but as FacesServlet is declared final I can not extend it and overwrite the init() method. In particular, I want to write some data to the database during development and testing, after hibernate has dropped and created the datamodel. Is there a way to configure Faces to run some method, e.g. in faces-config.xml? Or is it best to create a singleton bean that does the initialization?