Custom Validation MessageSource in Spring Boot – Spring Boot中的自定义验证消息源

最后修改: 2018年 8月 7日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

MessageSource is a powerful feature available in Spring applications. This helps application developers handle various complex scenarios with writing much extra code, such as environment-specific configuration, internationalization or configurable values.

MessageSource是Spring应用程序中的一项强大功能。这有助于应用程序开发人员处理各种复杂的情况,而无需编写很多额外的代码,例如特定环境的配置、国际化或可配置值。

One more scenario could be modifying the default validation messages to more user-friendly/custom messages.

还有一种情况是将默认的验证信息修改为更方便用户的/自定义的信息。

In this tutorial, we’ll see how to configure and manage custom validation MessageSource in the application using Spring Boot.

在本教程中,我们将看到如何使用Spring Boot配置和管理应用程序中的自定义验证MessageSource

2. Maven Dependencies

2.Maven的依赖性

Let’s start with adding the necessary Maven dependencies:

让我们从添加必要的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>

You can find the latest versions of these libraries over on Maven Central.

您可以在Maven Central找到这些库的最新版本。

3. Custom Validation Message Example

3.自定义验证信息示例

Let’s consider a scenario where we have to develop an application that supports multiple languages. If the user doesn’t provide the correct details as input, we’d like to show error messages according to the user’s locale.

让我们考虑一个场景,我们必须开发一个支持多种语言的应用程序。如果用户没有提供正确的细节作为输入,我们希望根据用户的地区设置来显示错误信息。

Let’s take an example of a Login form bean:

让我们举一个Login form bean的例子。

public class LoginForm {

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

    @NotNull
    private String password;

    // standard getter and setters
}

Here we’ve added validation constraints that verify if an email is not provided at all, or provided, but not following the standard email address style.

在这里,我们添加了验证约束,以验证是否根本没有提供电子邮件,或提供了电子邮件,但没有遵循标准的电子邮件地址样式。

To show custom and locale-specific message, we can provide a placeholder as mentioned for the @NotEmpty annotation.

为了显示自定义的和特定于本地的信息,我们可以提供一个占位符,就像提到的@NotEmpty注解。

The email.notempty property will be resolved from a properties files by the MessageSource configuration.

email.notempty属性将由MessageSource配置从属性文件中解决。

4. Defining the MessageSource Bean

4.定义MessageSource Bean

An application context delegates the message resolution to a bean with the exact name messageSource.

一个应用程序上下文将消息解析委托给一个名字确切的Bean messageSource。

ReloadableResourceBundleMessageSource is the most common MessageSource implementation that resolves messages from resource bundles for different locales:

ReloadableResourceBundleMessageSource是最常见的MessageSource实现,用于解析来自不同地域的资源包的消息。

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

Here, it’s important to provide the basename as locale-specific file names will be resolved based on the name provided.

在这里,提供basename是很重要的,因为特定于本地的文件名将根据所提供的名称来解决。

5. Defining LocalValidatorFactoryBean 

5.定义LocalValidatorFactoryBean

To use custom name messages in a properties file like we need to define a LocalValidatorFactoryBean and register the messageSource:

要在属性文件中使用自定义名称的消息,比如我们需要定义一个LocalValidatorFactoryBean并注册messageSource:

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

However, note that if we had already extended the WebMvcConfigurerAdapter, to avoid having the custom validator ignored, we’d have to set the validator by overriding the getValidator() method from the parent class.

然而,请注意,如果我们已经扩展了WebMvcConfigurerAdapter,为了避免自定义验证器被忽略,我们必须通过覆盖父类的getValidator()方法设置验证器。

Now we can define a property message like:

现在我们可以定义一个属性信息,比如。

email.notempty=<Custom_Message>”

email.notempty=<Custom_Message>”

instead of

而不是

“javax.validation.constraints.NotEmpty.message=<Custom_message>”

“javax.validation.constraints.NotEmpty.message=<Custom_message>”

6. Defining Property Files

6.定义属性文件

The final step is to create a properties file in the src/main/resources directory with the name provided in the basename in step 4:

最后一步是在src/main/resources目录下创建一个属性文件,名称为步骤4中basename提供的名称:

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

Here we can take advantage of internationalization along with this. Let’s say we want to show messages for a French user in their language.

在这里,我们可以同时利用国际化的优势。比方说,我们想用法语用户的语言为其显示信息。

In this case, we have to add one more property file with the name the messages_fr.properties in the same location (No code changes required at all):

在这种情况下,我们必须在同一位置添加一个名为messages_fr.properties的属性文件(完全不需要修改代码)。

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

7. Conclusion

7.结论

In this article, we covered how the default validation messages can be changed without modifying the code if the configuration is done properly beforehand.

在这篇文章中,我们介绍了如果事先做好配置,可以在不修改代码的情况下改变默认的验证信息。

We can also leverage the support of internationalization along with this to make the application more user-friendly.

我们还可以同时利用国际化的支持,使应用程序更加方便用户。

As always, the full source code is available over on GitHub.

一如既往,完整的源代码可在GitHub上获得