何时使用Jersey的@Singleton注释? [英] When to use @Singleton annotation of Jersey?

查看:706
本文介绍了何时使用Jersey的@Singleton注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个RESTful Web服务,同时阅读泽西岛文档我遇到了一个注释 @Singleton

I am developing a RESTful Web Service and while reading the Jersey documentation I came across an annotation @Singleton

在我的网络服务中,我主要是基于作为参数提供的唯一键。
当Student_Id通过时,类比将返回学生的所有信息。

In my web service I am mostly returning data based on the unique keys provided as parameter. An analogy would be return all the information of a Student when the Student_Id is passed.

所以我的问题是 @Singleton 适用于此类Web服务吗?

So my question is when @Singleton would be suited in such kind of Web Services?

根据的文档@RequestScoped


如果在请求处理中多次使用资源,则始终使用相同的实例。

If the resource is used more than one time in the request processing, always the same instance will be used.

那么在这种情况下我们不应该费心去使用 @Singleton 吧?

Then in that case we should not bother to use @Singleton right?

还有什么可能是我们必须为每个请求创建一个新实例的用例?

Also what could be the use cases where we have to make a new instance for every request?

I确实看了这个帖子,但我的问题不是回答。

I did have a look at this post but my question was not answered.

推荐答案

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

By default Jersey creates a new instance of the resource class for every request. So if you don't annotate the Jersey resource class, it implicitly uses @RequestScoped scope. It is stated in Jersey documentation:


默认生命周期(当没有注释时应用)。在此
范围内,为每个新请求创建资源实例,并使用
来处理此请求。如果资源在请求处理中使用了多于
的时间,则始终使用相同的实例。
当资源是子资源在匹配期间返回更多
次时,可能会发生这种情况。在这种情况下,只有实例将
服务器请求。

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.

大多数情况下你使用这个默认设置所以你没有使用 @Singleton 范围。您还可以使用 @Singleton 注释创建单例Jersey资源类。然后你需要在 MyApplication 类中注册单例类,例如,

Most cases you use this default setting so you don't use @Singleton scope. You can also create a singleton Jersey resource class by using @Singleton annotation. Then you need to register the singleton class in the MyApplication class, e.g.,

@Path("/resource")
@Singleton
public class JerseySingletonClass {
    //methods ...
}

public class MyApplication extends ResourceConfig {

    /*Register JAX-RS application components.*/
    public MyApplication () {
        register(JerseySingletonClass.class);
    }
}

这篇关于何时使用Jersey的@Singleton注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆