|
此版本仍在开发中,尚未视为稳定版。如需最新稳定版本,请使用 Spring Boot 4.0.4! |
验证
只要类路径中存在 JSR-303 实现(例如 Hibernate Validator),Bean Validation 1.1 支持的方法验证功能将自动启用。
这使得 Bean 方法可以在其参数和/或返回值上使用 jakarta.validation 约束进行注解。
包含此类注解方法的目标类,需要在类型级别上使用 @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 验证消息。
参数解析完成后,将使用 Bean 验证的默认插值器完成消息插值。
要自定义用于构建 ValidatorFactory 的 Configuration,请定义一个 ValidationConfigurationCustomizer Bean。
当定义了多个定制器 Bean 时,它们将根据其 @Order 注解或 Ordered 实现按顺序调用。