jersey jax-rs web服务中的初始化方法



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

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

我尝试使用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@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包中的@ApplicationScopedjavax.faces.bean包中的而不是 @ApplicationScoped

在EJB中使用@Startup@Singleton

在EJB中使用JAX-RS时,您可以尝试:

@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
    }
}

如果您对读取属性文件感兴趣,请勾选此问题。如果您正在使用CDI,并且愿意将Apache DeltaSpike依赖项添加到您的项目中,请考虑看看这个答案。

最新更新