Jersey jax-rs Web 服务中的初始化方法

init method in jersey jax-rs web service

我是 jax-rs 的新手,已经用 jersey 和 glassfish 构建了一个网络服务。

我需要的是一个方法,服务一启动就调用。在这个方法中我想加载一个自定义配置文件,设置一些属性,写一个日志等等......

我尝试使用 servlet 的构造函数,但每次调用 GET 或 POST 方法时都会调用构造函数。

我有哪些选择才能意识到这一点?

请告诉我,如果需要某些依赖项,请告诉我如何将其添加到 pom.xml(否则)

有多种方法可以实现它,具体取决于您的应用程序中可用的内容:

从 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 and @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.faces.bean 包中的 @ApplicationScoped from the javax.enterprise.context package and not @ApplicationScoped

使用来自 EJB 的 @Startup and @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
    }
}

如果您有兴趣阅读属性文件,请查看此 question. If you are using CDI and you are open to add Apache DeltaSpike dependencies to your project, considering having a look at this answer