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

Jor*_*rdi 1 jax-rs jakarta-ee

有什么方法可以检查 JAX-RS/Java EE 应用程序何时启动/部署?

此时,我想检查数据库是否已初始化。否则,只有在数据库没有初始化的情况下,才需要进行初始化,并且需要在Java EE应用程序启动时进行检查。

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

有任何想法吗?

cas*_*lin 5

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

使用ServletContextListener和Servlet API

由于 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
    }
}
Run Code Online (Sandbox Code Playgroud)

使用@ApplicationScoped和@Observes来自 CDI

将 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
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,您必须@ApplicationScoped从javax.enterprise.context包中使用,而不是@ApplicationScoped从javax.faces.bean包中使用。

使用@Startup和@Singleton来自 EJB

将 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
    }
}
Run Code Online (Sandbox Code Playgroud)