为什么 Jersey 会导致 singleton class 不工作?

Why does Jersey cause singleton class not working?

我实现了这样的东西:

@Path("/svc")
public class Service {

    Resource rsc = Resource.getInstance();

    @GET
    public String doGet() {...}
}

public class Resource {

    public static Resource instance;

    private Resource() {...}

    public static getInstance(){
        if (instance == null){
            return new Resource();
        }
        return instance;
    }
}

Service class 是实现 GETPOST 方法的地方,其中 Resource 是单例 class 其中一些数据是临时存储的。

然而,当我测试它时,我发现单例 class 每次调用方法时都会获得一个新实例。单例 class 只是一个 classic Java 单例实现。我知道添加 @Singleton 注释可以解决问题,但我想知道是什么导致了这种行为?

您还没有为实例变量赋值。

public class Resource{
      private static Resource instance;

      private Resource(){...}

      public static getInstance(){
        if(instance == null){
    instance = new Resource();

        }
        return instance;
      }    
}

因此,当您尝试 getInstance() 资源文件时。它始终为 null,这会导致为 class

创建新对象

JAX-WS Web 服务本身就是一个单例。这意味着所有请求都将使用单个 Web 服务实例(如 Servlet)处理。 参考这个link这里已经有了详细的答案Singleton Object in Java Web service

默认情况下,Jersey 为每个请求创建一个新的资源实例 class。因此,如果您不注释 Jersey 资源 class,它会隐式使用 @RequestScoped 范围。它在 Jersey 文档中有说明:

Default lifecycle (applied when no annotation is present). In this scope the resource instance is created for each new request and used for processing of this request. If the resource is used more than one time in the request processing, always the same instance will be used. This can happen when a resource is a sub resource is returned more times during the matching. In this situation only on instance will server the requests.

简答

你的单身人士 不是单身人士

长答案以及如何解决

instance 字段是 public,您总是返回一个新的 Resource 实例,而不是将其分配给 instance 字段。

还建议将您的 class 标记为 final 并在您的 getInstance() 方法中使用同步:

public final class Resource {

    private static Resource instance;

    private Resource() {

    }

    public static synchronized Resource getInstance() {
        if (instance == null) {
            instance = new Resource();
        }
        return instance;
    }
}

但是,这不是实现单例的最佳方式

更多信息,请参考What is an efficient way to implement a singleton pattern in Java?