Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - Instantiating an Errors object

Tags:

java

spring

I have a method like this:

public boolean validateMessage(String message, Errors errors) {   if (!StringUtils.hasLength(message)) {     errors.rejectValue(wrapperName + "message", "EMPTY_MESSAGE", EMPTY_MESSAGE_ERRORMSG) ;             return false ;         }         return true ;     } 

I want to call this method with a new Errors object, like:

boolean result = validateMessage("hi", new Errors()) ; 

However, this kind of instantiation is not allowed for Errors. Please advice.

If not with Errors, can I achieve this using an empty (new) BindingResult

like image 523
th3an0maly Avatar asked Oct 03 '12 17:10

th3an0maly


2 Answers

Errors and BindingResult are interfaces, therefore they cannot be instantiated. Your only option would be to use one of the classes which implements Errors.

You could use org.springframework.validation.BindException, this implements Errors - see here for details.

like image 118
Jonathan Avatar answered Oct 12 '22 23:10

Jonathan


Another option is to use org.springframework.validation.BeanPropertyBindingResult, which implements Errors. This object is of the same class of the BindingResult you recieve in Spring MVC controllers

Errors errors = new BeanPropertyBindingResult(objectToValidate, "objectName"); 
like image 31
Rober2D2 Avatar answered Oct 13 '22 00:10

Rober2D2