控制 JAX-RS 应用程序启动

Control JAX-RS application startup

首先,我是 JAX-RS 的新手。我正在尝试创建一个后端,并且我已经进行了 pom.xml 实施。更具体地说,我有这个 class

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("webapi")
public class MyApp extends Application {

}

而且我想知道如何控制它何时启动并最终停止启动。

像这样的东西:

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("webapi")
public class MyApp extends Application {

    @Override
    public void onStartup() {
        if (!Utils.isConfDataValid()) 
            exit(1);
    }

}

我现在对 JAX-RS 中的任何应用程序事件或类似事件有所了解。

谢谢!

请注意,某些类型的事件或挂钩取决于 Web 应用程序服务器。
在这种情况下,JAX-RS 与您要查找的内容无关。

另请注意,我不建议使用 System.exit 或终止这样的应用程序。


由于 JAX-RS 基于 Servlet 堆栈,您可以注册一个 ServletContextListener 实现以在上下文启动时执行代码。

public class CustomServletContextListener implements ServletContextListener {
   @Override
   public void contextInitialized(final ServletContextEvent servletContextEvent) {
      // Context startup
   }

   @Override
   public void contextDestroyed(final ServletContextEvent servletContextEvent) {
      // Context shutdown
   }
}

如果您处于 Servlet 3+ 环境

,可以通过使用 @WebListener 注释来注册此侦听器
@WebListener
public class CustomServletContextListener implements ServletContextListener {

否则你需要使用老式的 web.xml 文件,如 <listener-class>.