Is it good to use java static factory method in Spring Model Class for validate field with some kind of equation
java static factory methods in Spring Model class
118 Views Asked by rahuLrajaN AtThere are 2 best solutions below
On
No it is not a good to place java static factory method in Spring Model Class to validate fields.
This is a functionality, which have nothing to do with Model class. The purpose of model classes is to map SQL table data (or NoSQL data) to java POJO called Entity. Do not place any functionality there.
Validation process is a functionality, thus it is the best to place it into Service layer within Spring bean like @Service or @Component.
The less efficient method for validation is to use annotations on POJO attributes. Though those POJOs are should not be Entities, but Data Transfer Objects and they have to map incoming request data. I consider this not as good as to place validation in Spring beans because validation with annotations have limited functionality, and makes functional code placed in few places. Some of validation code will be at the DTO annotations and some validation within bean (Service). This is harder to read and maintain, then have everything in spring Service bean.
I would recommend to avoid this by the following reasons:
What you can probably do is adding custom validation annotation to the model. This validation will be executed by spring bean that implements some spec. This way you don't have above issues but still you can keep validation rule (without implementation details) on the model class.