对于最新的稳定版本,请使用 Spring Boot 3.4.0! |
验证
只要 JSR-303 实现(例如 Hibernate 验证器)在 Classpath 上,Bean Validation 1.1 支持的方法验证功能就会自动启用。
这允许 bean 方法使用jakarta.validation
对其参数和/或返回值的约束。
具有此类 Comments 方法的目标类需要使用@Validated
annotation 的 Comments,以便搜索其方法的内联约束 Comments。
例如,以下服务触发第一个参数的验证,确保其大小介于 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 Validation 的默认插值器完成消息插值。
要自定义Configuration
用于构建ValidatorFactory
中,定义一个ValidationConfigurationCustomizer
豆。
定义多个定制器 bean 时,将根据它们的@Order
annotation 或Ordered
实现。