I am developing a RESTful Web Service and while reading the Jersey documentation I came across an annotation @Singleton
In my web service I am mostly re
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.
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);
}
}