8

I have a resource to be exposed as Restful WS.If I have to make it Singleton, what is the preferred and advised way:

1 . Annotating the resource class using @Singleton

Or

2 . Implementing the getSingletons() method in my Application class implementation and instantiating the resource there like

   public class RestApplication extends Application {

    private Set<Object> singletons = new HashSet<Object>();

    public RestApplication() {
        singletons.add(new PlayerResource());
    }

    @Override
    public Set<Class<?>> getClasses() {
        return null;
    }

    @Override
    public Set<Object> getSingletons() {
        return singletons;
    }
}

I tried both ways and realised that both of them creates a singleton instance of the resource class, PlayerResource in this case.

Dhanush Gopinath
  • 5,652
  • 6
  • 37
  • 68
  • A similar question on Singletons was asked here as to the best implementation. Personally I would explicitly code the singleton pattern than use an annotation. See here: http://stackoverflow.com/questions/427902/java-enum-singleton – adamjmarkham Jun 29 '11 at 12:19
  • @AdamJMTech - my question is specific to Jersey/JAX-RS. Just wanted to know which on of them is the preferred way. Or what advantage either of them brings in. – Dhanush Gopinath Jun 29 '11 at 12:35

1 Answers1

0

For the most part, Everything technical you need to know has already been answered here.

For the rest of your answer, It doesn't really matter, as long as you are consistent throughout the code base.

The advantage of not using the annotation, is that if a module not provisioned by Jersey needs the resources, it will get the same singleton. (Like if you expect any third party plug-ins to interact with this resource)

The advantage to using the annotation is that you can let Jersey take care of the annoying/tedious stuff for you. (Like resource clean-up, if you use any close-able resources.)

Tezra
  • 8,463
  • 3
  • 31
  • 68