jersey-rs web服务中的init方法

Sur*_*ras 4 jax-rs init jersey

我是jax-rs的新手,并且已经建立了一个带有平针织物和玻璃鱼的网络服务.

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

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

我有什么选择才能意识到这一点?

请告诉我,如果需要一些依赖项,请告诉我如何将它添加到pom.xml(或其他)

cas*_*lin 10

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

使用ServletContextListenerServlet 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)

在这种方法中,您必须使用@ApplicationScopedjavax.enterprise.context封装, @ApplicationScopedjavax.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)

如果您有兴趣阅读属性文件,请检查此问题.如果您正在使用CDI并且您愿意将Apache DeltaSpike依赖项添加到您的项目中,请考虑查看此答案.