Manually call Spring Annotation Validation

JavaSpringHibernateValidationSpring Mvc

Java Problem Overview


I'm doing a lot of our validation with Hibernate and Spring Annotations like so:

public class Account {
    @NotEmpty(groups = {Step1.class, Step2.class})
    private String name;

    @NotNull(groups = {Step2.class})
    private Long accountNumber;

    public interface Step1{}
    public interface Step2{}
}

And then in the controller it's called in the arguments:

public String saveAccount(@ModelAttribute @Validated({Account.Step1.class}) Account account, BindingResult result) {
   //some more code and stuff here
   return "";
}

But I would like to decide the group used based on some logic in the controller method. Is there a way to call validation manually? Something like result = account.validate(Account.Step1.class)?

I am aware of creating your own Validator class, but that's something I want to avoid, I would prefer to just use the annotations on the class variables themselves.

Java Solutions


Solution 1 - Java

Spring provides LocalValidatorFactoryBean, which implements the Spring SmartValidator interface as well as the Java Bean Validation Validator interface.

// org.springframework.validation.SmartValidator - implemented by LocalValidatorFactoryBean
@Autowired
SmartValidator validator;

public String saveAccount(@ModelAttribute Account account, BindingResult result) {
    // ... custom logic
    validator.validate(account, result, Account.Step1.class);
    if (result.hasErrors()) {
        // ... on binding or validation errors
    } else {
        // ... on no errors
    }
    return "";
}

Solution 2 - Java

Here is a code sample from JSR 303 spec

Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

Driver driver = new Driver();
driver.setAge(16);
Car porsche = new Car();
driver.setCar(porsche);


Set<ConstraintViolation<Driver>> violations = validator.validate( driver );

So yes, you can just get a validator instance from the validator factory and run the validation yourself, then check to see if there are violations or not. You can see in the javadoc for Validator that it will also accept an array of groups to validate against.

Obviously this uses JSR-303 validation directly instead of going through Spring validation, but I believe spring validation annotations will use JSR-303 if it's found in the classpath

Solution 3 - Java

If you have everything correctly configured, you can do this:

@Autowired
Validator validator;

Then you can use it to validate you object.

Solution 4 - Java

This link gives pretty good examples of using validations in Spring apps. https://reflectoring.io/bean-validation-with-spring-boot/

I have found an example to run the validation programmitically in this article.

class MyValidatingService {
  
  void validatePerson(Person person) {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<Person>> violations = validator.validate(person);
    if (!violations.isEmpty()) {
      throw new ConstraintViolationException(violations);
    }
  } 
}

It throws 500 status, so it is recommended to handle it with custom exception handler.

@ControllerAdvice(annotations = RestController.class)
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<CustomErrorResponse> constraintViolationException(HttpServletResponse response, Exception ex) throws IOException {
        CustomErrorResponse errorResponse = new CustomErrorResponse();
        errorResponse.setTimestamp(LocalDateTime.now());
        errorResponse.setStatus(HttpStatus.BAD_REQUEST.value());
        errorResponse.setError(HttpStatus.BAD_REQUEST.getReasonPhrase());
        errorResponse.setMessage(ex.getMessage());
        return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
    }
}

Second example is from https://www.mkyong.com/spring-boot/spring-rest-error-handling-example/

Update: Using validation is persistence layer is not recommended: https://twitter.com/odrotbohm/status/1055015506326052865

Solution 5 - Java

Adding to answered by @digitaljoel, you can throw the ConstraintViolationException once you got the set of violations.

Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
		Set<ConstraintViolation<NotionalProviderPaymentDTO>> violations = validator.validate( notionalProviderPaymentDTO );
		
		if(!violations.isEmpty()) {
			throw new ConstraintViolationException(violations);
		}

You can create your own exception mapper which will handle ConstraintViolationException and send the errors messages to the client.

Solution 6 - Java

And also:

@Autowired
@Qualifier("mvcValidator")
Validator validator;

...
violations = validator.validate(account);

Solution 7 - Java

import javax.validation.Validator;
import javax.validation.ConstraintViolation;

public class{
	@Autowired
	private Validator validator;
       .
       .
    public void validateEmployee(Employee employee){

        Set<ConstraintViolation<Employee>> violations = validator.validate(employee);
        if(!violations.isEmpty()) {
            throw new ConstraintViolationException(violations);
        }
    }
}

Here, 'Employee' is a pojo class and 'employee' is it's object

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoss HettelView Question on Stackoverflow
Solution 1 - JavaPavel HoralView Answer on Stackoverflow
Solution 2 - JavadigitaljoelView Answer on Stackoverflow
Solution 3 - JavaJaiwo99View Answer on Stackoverflow
Solution 4 - JavansvView Answer on Stackoverflow
Solution 5 - JavaPrabjot SinghView Answer on Stackoverflow
Solution 6 - JavasupercobraView Answer on Stackoverflow
Solution 7 - JavaShibin FrancisView Answer on Stackoverflow