Jersey REST Server: instantiating resource classes

10,018

Solution 1

Jersey will establish a new instance of each class per request unless you annotate the class with @Singleton.

See: https://jersey.java.net/documentation/latest/jaxrs-resources.html#d0e2331

Solution 2

Actually according to this post default annotation type is change from singleton to per-request. Which means before one instance is used for every request but now create new class object for per-request. If you postwant to change it you can use resourceFactory annotation.

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ResourceFactory(SingletonProvider.class)
public @interface Singleton {}

Also you can check this link for com.sun.jersey.spi.resource JavaDoc

Share:
10,018
ktm5124
Author by

ktm5124

I'm a software engineer and computer scientist.

Updated on July 18, 2022

Comments

  • ktm5124
    ktm5124 almost 2 years

    A tutorial on the Jersey REST server [1] says of the Jersey servlet:

    This servlet analyzes the incoming HTTP request and selects the correct class and method to respond to this request. This selection is based on annotations in the class and methods.

    When the servlet "selects the correct class and method", does it re-instantiate the class every time? Or does it keep one instance of every resource class?

    This would seem to matter because, if these resources classes have references to objects that store application-wide state, these state objects would be re-instantiated along with the resources, and would not end up storing state data correctly.

    [1] http://www.vogella.com/articles/REST/article.html#restjersey

  • Rick-777
    Rick-777 about 9 years
    I think I understood that. But just use @Singleton