When validating objects using Validator interface (with supports() and validate() methods) I first make a class that implements Validator and then logically implement those two methods. After that I invoke it inside some controller. Question is related concurrency and thread safety and it is: do I make new instance of Validator each time I am validating something, or I can make Validator instance singleton and simple inject it in my controller? Can something go wrong if I use same instance of Validator for each REST request in controller?
Stefan Jankovic wrote:Can something go wrong if I use same instance of Validator for each REST request in controller?
If the Validator instance is thread-safe or, even better, immutable, then feel free to create a singleton and inject it. If it isn't, make it request scoped and still inject it. Let Spring worry about instantiating it.
I cannot speak with full authority on Spring validators specifically, but as a general rule, validators are stateless. Their primary purpose is to accept an input and return judgement with no long-term context. So no. Besides, if the validator is a Spring Bean, Spring Beans are by default singletons anyway.
I'm going to be a "small government" candidate. I'll be the government. Just me. No one else.