在JAX-RS / Java EE应用程序启动时执行操作

时间:2016-09-09 10:42:16

标签: java-ee jax-rs

有没有办法检查JAX-RS / Java EE应用程序何时启动/部署?

此时,我想检查数据库是否已初始化。否则,只有在数据库未初始化时,我才需要初始化它,我需要在Java EE应用程序启动时进行检查。

因此,我需要知道在JAX-RS / Java EE应用程序启动时是否有任何方法可以捕获。

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

至少有三种方法可以实现它:

使用Servlet API中的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
    }
}

使用CDI中的@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

使用EJB中的@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中完成,这可以注入一个数据库