何时使用 Jersey 的 @Singleton 注释? [英] When to use @Singleton annotation of Jersey?
问题描述
我正在开发 RESTful Web 服务,并在阅读 Jersey 文档 我遇到了一个注释 @Singleton
I am developing a RESTful Web Service and while reading the Jersey documentation I came across an annotation @Singleton
在我的网络服务中,我主要根据作为参数提供的唯一键返回数据.打个比方,当传递Student_Id时,返回一个Student的所有信息.
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
什么时候适合这种网络服务?
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 did have a look at this post but my question was not answered.
推荐答案
默认情况下,Jersey 为每个请求创建资源类的新实例.因此,如果您不注释 Jersey 资源类,它会隐式使用 @RequestScoped
范围.它在 泽西岛文档 中有说明:
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屋!