-
Notifications
You must be signed in to change notification settings - Fork 24
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: provide ValidationUtils by default
- Loading branch information
Showing
2 changed files
with
42 additions
and
0 deletions.
There are no files selected for viewing
41 changes: 41 additions & 0 deletions
41
...templates/${artifactId}-provider/src/main/java/${basePath}/util/ValidationUtils.tmpl.java
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
package ${basePackage}.util; | ||
|
||
import org.springframework.beans.factory.annotation.Autowired; | ||
import org.springframework.stereotype.Component; | ||
import org.springframework.validation.BeanPropertyBindingResult; | ||
import org.springframework.validation.BindException; | ||
import org.springframework.validation.BindingResult; | ||
import org.springframework.validation.beanvalidation.SpringValidatorAdapter; | ||
|
||
import javax.validation.Validator; | ||
|
||
@Component | ||
public class ValidationUtils { | ||
private static Validator validator; | ||
private static SpringValidatorAdapter springValidator; | ||
|
||
@Autowired | ||
public void setValidator(Validator validator) { | ||
ValidationUtils.validator = validator; | ||
ValidationUtils.springValidator = new SpringValidatorAdapter(validator); | ||
} | ||
|
||
/** | ||
* 校验参数,返回详细错误信息 | ||
*/ | ||
public static <T> BindingResult validate(T target, Class<?>... groups) { | ||
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(target, target.getClass().getName()); | ||
springValidator.validate(target, errors, groups); | ||
return errors; | ||
} | ||
|
||
/** | ||
* 校验参数,如果失败则抛出异常 | ||
*/ | ||
public static <T> void validateAndThrow(T target, Class<?>... groups) throws BindException { | ||
BindingResult errors = validate(target, groups); | ||
if (errors.hasErrors()) { | ||
throw new BindException(errors); | ||
} | ||
} | ||
} |
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