I want to map my Order
to distinct dtos for downstream services to consume. They accept the same DTO, but requires different fields.
For example, my service is A, I will send OutboundOrderDto
to B and C, and for B, order.cart.shippingAddress
is mandatory, but for C, instead, order.cart.billingAddress
is mandatory.
How can I use Spring Boot JSR 303 validation and activate different rules for each service, so that in the method sendOutbound(OutboundOrderDto dto)
, I just need to add @Validated
before the arg to catch maybe-null fields errors and stop sending?
All I see now is to define 2 DTOs, but I think maybe there are easier ways.
Later I found that validation group can be used, as in the documentation:
https://beanvalidation.org/1.0/spec/#constraintdeclarationvalidationprocess-groupsequence
And, as @areus suggested, groups should be used with caution, as per https://reflectoring.io/bean-validation-with-spring-boot/#using-validation-groups-to-validate-objects-differently-for-different-use-cases
Quote:
Careful with Validation Groups Using validation groups can easily become an anti-pattern since we're mixing concerns. With validation groups the validated entity has to know the validation rules for all the use cases (groups) it is used in. More on this topic in my article about Bean Validation anti-patterns .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.