Spring Service method validation
It is considered a good practice to validate the inputs of your service method.
You need to first annotate your service class with
In order to avoid a
If the input is invalid, a
You need to first annotate your service class with
@Validated
. This annotation tells Spring to evaluate the constraints annotations on each method parameters.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Service | |
@Transactional(readOnly = true) | |
@Validated | |
public class ClientProductServiceImpl implements ClientProductService { | |
@Override | |
@Transactional | |
public ClientProduct save(Long sourceProductId, @Valid ClientProductDto clientProductDto) {...} | |
} | |
In order to avoid a
ConstraintDeclarationException
, your interface should also declare the constraint annotations.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface ClientProductService { | |
ClientProduct save(Long sourceProductId, @Valid ClientProductDto clientProductDto); | |
} |
If the input is invalid, a
ConstraintViolationException
is thrown.
Comments
Post a Comment