bean-validation + spring example

Add bean validation dependency

Hibernate provides an implementation of bean-validation. So we will dependent on it. But it has nothing to do with Hiberante ORM.


Create a validator class as a spring bean


public class MyBeanValidator {

	private Validator validator;

	public <T> List<String> validateBean(T bean) {
		List<string> errors = new ArrayList<string>();
		Set<ConstraintViolation<T> violations = validator.validate(bean);
		for (ConstraintViolation<T> violation : violations) {
		return errors;

	public void setValidator(Validator validator) {
		this.validator = validator;


Use It

@ContextConfiguration(locations = { "/spring/applicationContext-test.xml" })
public class MyBeanValidatorITCase {

	MyBeanValidator myBeanValidator;


	public void validateBean_InvalidProp() {
		Mb mb = new Mb();
		List<String> errors = myBeanValidator.validateBean(mb, "bean-null");
		Assert.assertEquals(2, errors.size());

	public void validateBean_NoErrors() {
		Mb mb = new Mb(); = "";
		mb.password = "heyya";
		List<String> errors = myBeanValidator.validateBean(mb, "bean-null");
		Assert.assertEquals(0, errors.size());


	private static class Mb {

		@NotNull(message = "email-null")
		private String email;

		@NotNull(message = "password-null")
		private String password;


Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.