问题
I would like to listen if a JSF application is started or stopped like as possible with a ServletContextListener
in a plain Servlet web application. How can I achieve this?
回答1:
You can use an @ApplicationScoped @ManagedBean which is eagerly initialized and annotate the desired startup/shutdown hook methods with @PostConstruct and @PreDestroy respectively.
So:
@ManagedBean(eager=true)
@ApplicationScoped
public class App {
@PostConstruct
public void init() {
// ...
}
@PreDestroy
public void destroy() {
// ...
}
}
Please note that this does not mean that you can't use a ServletContextListener
in a JSF webapp. JSF is built on top of the Servlet API which thus means that you could just continue using it. With the new Servlet 3.0 @WebListener annotation, it's also possible to configure it without need for web.xml
:
@WebListener
public class Config implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
// ...
}
@Override
public void contextDestroyed(ServletContextEvent event) {
// ...
}
}
回答2:
You could provide a system event listener for this. See this blogpost for further details: Bootstrapping JSF applications with system events
来源:https://stackoverflow.com/questions/12177795/is-there-something-like-a-servletcontextlistener-in-jsf