Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
961 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...