有没有办法检查JAX-RS / Java EE应用程序何时启动/部署?
此时,我想检查数据库是否已初始化。否则,只有在数据库未初始化时,我才需要初始化它,我需要在Java EE应用程序启动时进行检查。
因此,我需要知道在JAX-RS / Java EE应用程序启动时是否有任何方法可以捕获。
有什么想法吗?
答案 0 :(得分:3)
至少有三种方法可以实现它:
ServletContextListener
一旦JAX-RS构建在Servlet API的顶部,下面的代码就可以解决这个问题:
@WebListener
public class StartupListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
// Perform action during application's startup
}
@Override
public void contextDestroyed(ServletContextEvent event) {
// Perform action during application's shutdown
}
}
@ApplicationScoped
和@Observes
将JAX-RS与CDI一起使用时,您可以拥有以下内容:
@ApplicationScoped
public class StartupListener {
public void init(@Observes
@Initialized(ApplicationScoped.class) ServletContext context) {
// Perform action during application's startup
}
public void destroy(@Observes
@Destroyed(ApplicationScoped.class) ServletContext context) {
// Perform action during application's shutdown
}
}
请注意,您必须使用javax.enterprise.context
包中的@ApplicationScoped
,而不是javax.faces.bean
包中的@ApplicationScoped
。
@Startup
和@Singleton
将JAX-RS与EJB一起使用时,您可以尝试:
@Startup
@Singleton
public class StartupListener {
@PostConstruct
public void init() {
// Perform action during application's startup
}
@PreDestroy
public void destroy() {
// Perform action during application's shutdown
}
}
答案 1 :(得分:0)
虽然它可能不是你想要做的事情,但这样的事情可能最好在一个带有@Singleton
和@Startup
的bean中完成,这可以注入一个数据库