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.

			
			
				org.hibernate
				hibernate-validator
				5.1.3.Final
			

Create a validator class as a spring bean

		

@Component 
public class MyBeanValidator {

	@Resource 
	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) {
			errors.add(violation.getMessage());
		}
		return errors;
	}

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

}

Use It

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

	@Resource
	MyBeanValidator myBeanValidator;

 

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

	@Test
	public void validateBean_NoErrors() {
		Mb mb = new Mb();
		mb.email = "hi@hi.com";
		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.