驗證

只要類別路徑上有 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
	}

}

當解析限制訊息中的 {parameters} 時,會使用應用程式的 MessageSource。這讓您可以使用應用程式的 messages.properties 檔案來處理 Bean Validation 訊息。一旦參數解析完成,訊息內插就會使用 Bean Validation 的預設內插器完成。

若要自訂用於建置 ValidatorFactoryConfiguration,請定義 ValidationConfigurationCustomizer bean。當定義多個自訂器 bean 時,會根據其 @Order 註解或 Ordered 實作依序呼叫它們。