驗證

只要 classpath 中存在 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
	}

}

應用程式的 MessageSource 用於解析約束訊息中的 {parameters}。這允許您將應用程式的 messages.properties 檔案用於 Bean Validation 訊息。引數解析後,訊息插值將使用 Bean Validation 的預設插值器完成。

要自定義用於構建 ValidatorFactoryConfiguration,請定義一個 ValidationConfigurationCustomizer bean。當定義了多個自定義器 bean 時,它們會根據其 @Order 註解或 Ordered 實現按順序呼叫。

© . This site is unofficial and not affiliated with VMware.