Validation
由 Bean Validation 1.1 支持的方法验证特性会自动启用,只要类路径上有 JSR-303 实现(例如 Hibernate 验证器)。这可以让 Bean 方法的参数和/或返回值使用 jakarta.validation
约束进行注释标记。此类注释方法的目标类需要在类型级别使用 @Validated
注释标记,以便在其方法中搜索内嵌约束注释标记。
The method validation feature supported by Bean Validation 1.1 is automatically enabled as long as a JSR-303 implementation (such as Hibernate validator) is on the classpath.
This lets bean methods be annotated with jakarta.validation
constraints on their parameters and/or on their return value.
Target classes with such annotated methods need to be annotated with the @Validated
annotation at the type level for their methods to be searched for inline constraint annotations.
例如,以下服务会触发第一个参数的验证,确保其大小介于 8 和 10 之间:
For instance, the following service triggers the validation of the first argument, making sure its size is between 8 and 10:
解析约束消息中的 {parameters}
时,会使用应用程序的 MessageSource
。这允许你对 Bean Validation 消息使用 your application’s messages.properties
files。在解析了参数后,会使用 Bean Validation 的默认插值器完成消息插值。
The application’s MessageSource
is used when resolving {parameters}
in constraint messages.
This allows you to use your application’s messages.properties
files for Bean Validation messages.
Once the parameters have been resolved, message interpolation is completed using Bean Validation’s default interpolator.
若要自定义用于构建 ValidatorFactory
的 Configuration
,请定义一个 ValidationConfigurationCustomizer
bean。当定义了多个自定义器 bean 时,会根据其 @Order
注释或 Ordered
实现按顺序调用它们。
To customize the Configuration
used to build the ValidatorFactory
, define a ValidationConfigurationCustomizer
bean.
When multiple customizer beans are defined, they are called in order based on their @Order
annotation or Ordered
implementation.