Spring 具有可用于验证对象的界面。该接口通过使用对象来工作,以便在验证时, 验证者可以向对象报告验证失败。ValidatorValidatorErrorsErrors

请考虑以下小型数据对象的示例:

  • Java

  • Kotlin

public class Person {

	private String name;
	private int age;

	// the usual getters and setters...
}
class Person(val name: String, val age: Int)

下一个示例通过实现 以下两种接口方法:Personorg.springframework.validation.Validator

  • supports(Class):这可以验证提供的实例吗?ValidatorClass

  • validate(Object, org.springframework.validation.Errors):验证给定对象 并且,如果出现验证错误,则将这些错误注册到给定对象。Errors

实现 a 是相当简单的,特别是当你知道 Spring 框架也提供的帮助程序类时。以下 实例的示例实现:ValidatorValidationUtilsValidatorPerson

  • Java

  • Kotlin

public class PersonValidator implements Validator {

	/**
	 * This Validator validates only Person instances
	 */
	public boolean supports(Class clazz) {
		return Person.class.equals(clazz);
	}

	public void validate(Object obj, Errors e) {
		ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
		Person p = (Person) obj;
		if (p.getAge() < 0) {
			e.rejectValue("age", "negativevalue");
		} else if (p.getAge() > 110) {
			e.rejectValue("age", "too.darn.old");
		}
	}
}
class PersonValidator : Validator {

	/**
	 * This Validator validates only Person instances
	 */
	override fun supports(clazz: Class<*>): Boolean {
		return Person::class.java == clazz
	}

	override fun validate(obj: Any, e: Errors) {
		ValidationUtils.rejectIfEmpty(e, "name", "name.empty")
		val p = obj as Person
		if (p.age < 0) {
			e.rejectValue("age", "negativevalue")
		} else if (p.age > 110) {
			e.rejectValue("age", "too.darn.old")
		}
	}
}

类上的方法用于 如果属性是,则拒绝该属性或空字符串。看一看 ValidationUtils javadoc 查看除了前面显示的示例之外,它还提供哪些功能。staticrejectIfEmpty(..)ValidationUtilsnamenull

虽然当然可以实现单个类来验证每个 在富对象中的嵌套对象中,最好封装验证 每个嵌套类对象在其自己的实现中的逻辑。一个简单的 “丰富”对象的示例是由两个属性(第一个和第二个名称)和一个复杂对象组成的 A。 对象 可以独立于对象使用,因此已经实现了不同的。如果您希望重用所包含的逻辑 在类中,无需求助于复制和粘贴,您可以 依赖注入或实例化 在你的 , 如以下示例所示:ValidatorValidatorCustomerStringAddressAddressCustomerAddressValidatorCustomerValidatorAddressValidatorAddressValidatorCustomerValidator

  • Java

  • Kotlin

public class CustomerValidator implements Validator {

	private final Validator addressValidator;

	public CustomerValidator(Validator addressValidator) {
		if (addressValidator == null) {
			throw new IllegalArgumentException("The supplied [Validator] is " +
				"required and must not be null.");
		}
		if (!addressValidator.supports(Address.class)) {
			throw new IllegalArgumentException("The supplied [Validator] must " +
				"support the validation of [Address] instances.");
		}
		this.addressValidator = addressValidator;
	}

	/**
	 * This Validator validates Customer instances, and any subclasses of Customer too
	 */
	public boolean supports(Class clazz) {
		return Customer.class.isAssignableFrom(clazz);
	}

	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "field.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "surname", "field.required");
		Customer customer = (Customer) target;
		try {
			errors.pushNestedPath("address");
			ValidationUtils.invokeValidator(this.addressValidator, customer.getAddress(), errors);
		} finally {
			errors.popNestedPath();
		}
	}
}
class CustomerValidator(private val addressValidator: Validator) : Validator {

	init {
		if (addressValidator == null) {
			throw IllegalArgumentException("The supplied [Validator] is required and must not be null.")
		}
		if (!addressValidator.supports(Address::class.java)) {
			throw IllegalArgumentException("The supplied [Validator] must support the validation of [Address] instances.")
		}
	}

	/*
	* This Validator validates Customer instances, and any subclasses of Customer too
	*/
	override fun supports(clazz: Class<>): Boolean {
		return Customer::class.java.isAssignableFrom(clazz)
	}

	override fun validate(target: Any, errors: Errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "field.required")
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "surname", "field.required")
		val customer = target as Customer
		try {
			errors.pushNestedPath("address")
			ValidationUtils.invokeValidator(this.addressValidator, customer.address, errors)
		} finally {
			errors.popNestedPath()
		}
	}
}

验证错误将报告给传递给验证程序的对象。在案例中 的Spring Web MVC,您可以使用标签来检查错误消息,但是 您也可以自己检查对象。有关 它提供的方法可以在 Javadoc 中找到。Errors<spring:bind/>Errors

验证器也可以在本地调用,以立即验证给定对象, 不涉及绑定过程。从 6.1 开始,这已通过一种新方法进行了简化,该方法现在默认可用,返回 可以检查的简单“错误”表示:通常调用或将错误摘要消息转换为异常的新方法 (例如)。Validator.validateObject(Object)hasErrors()failOnErrorvalidator.validateObject(myObject).failOnError(IllegalArgumentException::new)