知識庫 / Spring / Spring Boot RSS 訂閱

Spring Boot 自定義驗證消息源

Spring Boot
HongKong
4
01:43 PM · Dec 06 ,2025

1. 概述

MessageSource 是 Spring 應用中一個強大的特性,它幫助應用開發者處理各種複雜的場景,無需編寫大量的額外代碼,例如環境特定的配置、國際化或可配置的值。

另一個場景是修改默認的驗證消息為更用户友好/自定義消息。

在本教程中,我們將學習如何使用 Spring Boot 配置和管理應用程序中的自定義驗證 MessageSource

2. Maven 依賴

讓我們從添加必要的 Maven 依賴開始:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

您可以在 Maven Central 上找到這些庫的最新版本:Maven Central

3. 自定義驗證消息示例

讓我們考慮一個需要開發支持多語言的應用程序的場景。如果用户沒有提供正確的輸入信息,我們希望根據用户的區域設置顯示相應的錯誤消息。

以下是一個登錄表單 Bean 的示例:

public class LoginForm {

    @NotEmpty(message = "{email.notempty}")
    @Email
    private String email;

    @NotNull
    private String password;

    // standard getter and setters
}

我們已添加驗證約束,以確保電子郵件未提供,或提供但未遵循標準電子郵件地址樣式。

為了顯示自定義和特定於區域的消息,我們可以為 @NotEmpty 註解提供佔位符。

通過 MessageSource 配置,email.notempty 屬性將從屬性文件解析。

4. 定義 MessageSource Bean

應用程序上下文將消息解析委託給名為 messageSource 的 Bean。

ReloadableResourceBundleMessageSource 是最常見的 MessageSource 實現,它通過從不同區域語言的資源包中解析消息來解決消息:

@Bean
public MessageSource messageSource() {
    ReloadableResourceBundleMessageSource messageSource
      = new ReloadableResourceBundleMessageSource();
    
    messageSource.setBasename("classpath:messages");
    messageSource.setDefaultEncoding("UTF-8");
    return messageSource;
}

在這裏,重要的是提供 basename,因為本地化特定文件名的解析將基於提供的名稱進行。

5. 定義 LocalValidatorFactoryBean

為了在 properties 文件中使用自定義名稱消息,我們需要定義 LocalValidatorFactoryBean 並註冊 messageSource

@Bean
public LocalValidatorFactoryBean getValidator() {
    LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
    bean.setValidationMessageSource(messageSource());
    return bean;
}

但是請注意,如果我們在已經擴展了<em>WebMvcConfigurerAdapter</em>之後,為了避免自定義驗證器被忽略,我們需要通過重寫父類中的<em>getValidator()</em>方法來設置驗證器。

現在我們可以定義一個消息屬性,例如:

“<em>email.notempty=<Custom_Message></em>”

而不是

<em>“jakarta.validation.constraints.NotEmpty.message=<Custom_message>”</em>

6. 定義屬性文件

最後一步是在 src/main/resources 目錄下創建一個名稱與步驟 4 中 basename 提供的名稱相同的屬性文件:

# messages.properties
email.notempty=Please provide valid email id.

在這裏,我們可以利用國際化這一特性。 假設我們想要向法語用户顯示他們語言中的消息。

在這種情況下,我們需要在同一位置添加一個名為 messages_fr.properties 的額外屬性文件(無需進行任何代碼更改):

# messages_fr.properties
email.notempty=Veuillez fournir un identifiant de messagerie valide.

7. 結論

在本文中,我們介紹瞭如何通過正確配置,在不修改代碼的情況下更改默認驗證消息。

此外,我們還可以利用國際化支持,使應用程序更具用户友好性。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.