验证

只要 classpath 中存在 JSR-303 实现(例如 Hibernate Validator),Bean Validation 1.1 支持的方法验证功能就会自动启用。这允许使用 jakarta.validation 约束来注解 bean 方法的参数和/或返回值。具有此类注解方法的目​标类需要使用类型级别的 @Validated 注解进行注解,以便在其方法中搜索内联约束注解。

例如,以下服务会触发对第一个参数的验证,确保其大小在 8 到 10 之间

  • Java

  • Kotlin

import jakarta.validation.constraints.Size;

import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

@Service
@Validated
public class MyBean {

	public Archive findByCodeAndAuthor(@Size(min = 8, max = 10) String code, Author author) {
		return ...
	}

}
import jakarta.validation.constraints.Size
import org.springframework.stereotype.Service
import org.springframework.validation.annotation.Validated

@Service
@Validated
class MyBean {

	fun findByCodeAndAuthor(code: @Size(min = 8, max = 10) String?, author: Author?): Archive? {
		return null
	}

}

应用程序的 MessageSource 用于解析约束消息中的 {parameters}。这允许您将应用程序的 messages.properties 文件用于 Bean Validation 消息。参数解析后,消息插值将使用 Bean Validation 的默认插值器完成。

要自定义用于构建 ValidatorFactoryConfiguration,请定义一个 ValidationConfigurationCustomizer bean。当定义了多个自定义器 bean 时,它们会根据其 @Order 注解或 Ordered 实现按顺序调用。

© . This site is unofficial and not affiliated with VMware.