java - 在 Java Jersey 2 JAX-RS 中初始化单例

标签 java rest jersey jax-rs

我是 Jersey (2.22.2) 的新手,请耐心等待。我正在创建一个与 LDAP 服务器交互的 REST 服务,用于存储、删除和检索用户数据。该服务通过执行加密/解密充当安全中介。

在使用 REST 服务之前必须进行相当多的初始化,并且我只想执行一次此初始化(当应用程序部署在服务器上时)。因此该服务将作为单例运行。

如果有人能给我一些关于执行此操作的最佳方法的指示,我将不胜感激?谢谢!

最佳答案

Jersey 2.22.2 具有更改其资源生命周期的内置支持。您可以使用@Singleton注释。请阅读官方文档 JAX-RS Application, Resources and Sub-Resources: Life-cycle of Root Resource Classes 来了解它。 。只需将初始化代码放入资源的默认构造函数中即可。

  • Scope: Singleton
  • Annotation: @Singleton
  • Annotation full class name: javax.inject.Singleton

In this scope there is only one instance per jax-rs application. Singleton resource can be either annotated with @Singleton and its class can be registered using the instance of Application. You can also create singletons by registering singleton instances into Application.

示例:

package com.airhacks;
import java.util.Date;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

@Path("/hello")
@Singleton
public class HelloWorldService {

    public HelloWorldService() throws InterruptedException {
        // Some expensive initialization goes here.
        Thread.sleep(5000);
        System.out.println("Initialized at " + new Date());
    }

    @GET
    public Response getMsg() {
        String output = "Hello world at " + new Date();
        return Response.status(200).entity(output).build();
    }

}

在上面的示例中,由于 Glassfish 3 上的延迟初始化,第一个请求花费了 5 秒,然后立即处理所有后续请求。

关于java - 在 Java Jersey 2 JAX-RS 中初始化单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36186102/

相关文章:

java - "double[] array = {1,2,3,4};"与 "double[] array = new double[]{1,2,3,4,};"

java - 取消匿名TimerTask

python - 属性错误 : 'DeferredAttribute' object has no attribute 'rel'

javascript - 是否可以创建一个只允许某些域调用的 javascript api

json - 配置JsonProcessingExceptionMapper登录Dropwizard

java - 使用jsoup解析网站数据

java - Java 中的正则表达式将非空白字符串分解为单个字符和数字 block

java - 用于网络错误处理的 Jersey API

java - 无法使用 Jackson 创建内部类列表

java - 将 Jetty 与 JAX-RS-Jersey 集成