users@jersey.java.net

[Jersey] Re: Singleton resources in JAX-RS

From: Jakub Podlesak <jakub.podlesak_at_oracle.com>
Date: Mon, 5 Aug 2013 11:22:14 +0200

Hi Arun,

If you do *not* mark a resource class as a singleton (with @Singleton annotation),
a new instance would get created for each request. I presume, that is why you
saw two instances created (i presume you made two requests?).
Or have you seen two instances even in the @Singleton case?
In such a case there might indeed be a bug in Jersey.
Could you please clarify?

Otherwise it is as you wrote, you can either leave it up to Jersey runtime
to instantiate (and inject) resources/providers, or you directly register pre-populated
instances to be used by the runtime.

Cheers,

~Jakub

On Aug 3, 2013, at 7:35 AM, Arun Gupta <arun.p.gupta_at_oracle.com> wrote:

> Created an Application class as:
>
> @ApplicationPath("webresources")
> public class MyApplication extends Application {
>
> @Override
> public Set<Object> getSingletons() {
> Set<Object> resources = new java.util.HashSet<>();
> resources.add(new MyResource());
> return resources;
> }
> }
>
> This is a user-managed resource where the constructor is explicitly invoked by the application. I like the API for:
>
> public Set<Class<?>> getClasses() {
> Set<Class<?>> resources = new java.util.HashSet<>();
> resources.add(MyResource.class);
> return resources;
> }
>
> where the resources are managed by the container. Any thoughts on why the APIs are different ?
>
> Can this singeleton resource be container-managed instead ? There is @Singleton which makes it container-managed. Is that a conscious decision ?
>
> The resource has a method as:
>
> @PostConstruct
> void init() {
> strings = new ArrayList<>();
> System.out.println("******* init");
> }
>
> Of course, the init method is not called in this case because the resource is application-managed. I changed it to:
>
> public MyResource() {
> strings = new ArrayList<>();
> System.out.println("******* init");
> }
>
> and now the constructor is invoked twice based upon the output in server.log. The constructor is correctly invoked once if the resource is marked with @Singleton instead of returned from the getSingletons() method. Bug in Jersey ?
>
> Arun
>
> --
> http://twitter.com/arungupta
> http://blogs.oracle.com/arungupta
>