驗證
只要類路徑中存在 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
}
}
在解析約束訊息中的 {parameters}
時,將使用應用的 MessageSource
。這允許你將 應用的 messages.properties
檔案用於 Bean Validation 訊息。一旦引數被解析,訊息插值將使用 Bean Validation 的預設插值器完成。
要自定義用於構建 Configuration
的 ValidatorFactory
,請定義一個 ValidationConfigurationCustomizer
bean。當定義了多個定製器 bean 時,它們將根據其 @Order
註解或 Ordered
實現按順序呼叫。