@Singleton or getSingletons() while implementing Singleton Resources in Jersey
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;
}
开发者_StackOverflow
@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.
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.)
精彩评论