When to use @Singleton in a Jersey resource

前端 未结 2 793
天命终不由人
天命终不由人 2021-02-14 11:56

I have a Jersey resource that access the database. Basically it opens a database connection in the initialization of the resource. Performs queries on the resource\'s methods.

2条回答
  •  萌比男神i
    2021-02-14 12:33

    Rather than thinking about making the resource a singleton, focus more on managing backend, service type objects like your ResponseGenerator class as singletons, which obviously shouldn't be instantiated every request.

    Making the resource a singleton as well is one way of managing ResponseGenerator as a singleton, but it's not the only or necessarily the best way, see Access external objects in Jersey Resource class and How to wire in a collaborator into a Jersey resource? for ways to inject this into non-singleton resources.

    Note that your ResponseGenerator class would need work before it would function as a singleton, whether injected into a per-request resource or instantiated in a singleton resource. It's not thread safe, and you would open a single connection on startup and reuse it across requests, which won't work, you should use a connection pool to do the heavy lifting of efficiently + safely reusing connections across requests.

    Some comments on best practices for the code will also be helpful.

    You'll get better responses on http://codereview.stackexchange.com, but:

    • ResponseGenerator is a poor name for a class (just about everything in a web application is a response generator).

    • don't use String as the return type of your service and object, use proper typed objects (eg it sounds like you're returning a java.util.List of something).

    • Don't swallow your SQLException, bubble it up to allow Jersey to generate a 5xx series response code in your resource.

    • Use final member variables.

    • Your log object should be static.

提交回复
热议问题