I'm making Java REST application. I wonder how should I implement my services - should I use static service variables for whole application or make services as singletons like it was made in Spring MVC. Is there any difference between singleton object and initializing object only once during application?
should I use static service variables for whole application or make services as singletons
It depends. You have to ask yourself two questions to come up with an answer:
static variable
stored?You have 2 Options:
final class Services
which holds all available services as public static final
variables.public static final
variable, called INSTANCE
You see that the first point will have all classes in the same place. Could possibly get clustered, unreadable and not very easy to maintain.
For the second point you're almost approaching the singleton case.
You again have 2 Options:
public static final
variable in the service class and create an instance directly.The first point has it's upsides. If you need to allocate resources or need to do any other "heavy" operation. This works, and is thread safe
For the second point you see that it's like the second point from the first question.
As said, it depends on the use case. I would probably use a singleton always. Because then all the logic regarding it's state and availability are all held in one place.