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 @Validated. This annotation tells Spring to evaluate the constraints annotations on each method parameters.

@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.

public interface ClientProductService {
ClientProduct save(Long sourceProductId, @Valid ClientProductDto clientProductDto);
}


If the input is invalid, a ConstraintViolationException is thrown.

Comments

Popular posts from this blog

Spring JPA : Using Specification with Projection

Chip input using Reactive Form