|
如需获取最新稳定版本,请使用 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 Validation 消息。
一旦参数被解析,消息插值将使用 Bean Validation 的默认插值器完成。
要自定义用于构建 ValidatorFactory 的 Configuration,请定义一个 ValidationConfigurationCustomizer Bean。
当定义了多个自定义器Bean时,它们将根据其 @Order 注解或 Ordered 实现顺序依次调用。