[Jersey] Singleton resources in JAX-RS

From: Arun Gupta <>
Date: Fri, 02 Aug 2013 22:35:43 -0700

Created an Application class as:

public class MyApplication extends Application {

     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<>();
         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:

     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 ?