users@jersey.java.net

[Jersey] Singleton resources in JAX-RS

From: Arun Gupta <arun.p.gupta_at_oracle.com>
Date: Fri, 02 Aug 2013 22:35:43 -0700

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