Java – use @ singleton or getsingletons() when implementing singleton resources in Jersey

I have a resource that can be exposed as restful WS If I have to make it a singleton, what are the preferred and recommended ways:

1. Annotate the resource class with @ singleton

or

2. Implement the getsingletons () method in my application class implementation and instantiate resources there

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 methods and realized that they both created singleton instances of resource classes, in this case playerresource

Solution

In most cases, all the techniques you need to know have answered here

For the rest of your answers, it doesn't matter as long as you keep consistent throughout the code base

The advantage of not using annotations is that if Jersey does not have a configured module that requires resources, it will get the same singleton (just as you want any third-party plug-ins to interact with this resource)

The advantage of using annotations is that you can let Jersey handle annoying / boring things for you (just like resource cleanup, if you use any available resources.)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>