Chris
Chris

Reputation: 984

How can I initialize a Java FacesServlet

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?

Upvotes: 3

Views: 2297

Answers (3)

BalusC
BalusC

Reputation: 1109322

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.

Upvotes: 7

tartak
tartak

Reputation: 485

Hey you may want to use some aspects here. Just set it to run before

     void   init(ServletConfig servletConfig) 
      //Acquire the factory instances we will 

//this is from here

Maybe this will help you.

Upvotes: 0

Adrian Mitev
Adrian Mitev

Reputation: 4752

You could implement your own ServletContextListener that gets notified when the web application is started. Since it's a container managed you could inject resources there are do whatever you want to do. The other option is to create a @Singleton ejb with @Startup and do the work in it's @PostCreate method. Usually the ServletContextListener works fine, however if you have more than one web application inside an ear and they all share the same persistence context you may consider using a @Singleton bean.

Upvotes: 0

Related Questions