How to configure SpringBoot Validation prompt information internationalization
Spring Boot Validation supports JSR-380 (aka. Bean Validation 2.0, part of Jakarta EE and JavaSE) annotations. The verification error message can be set through the message attribute of the verification annotation, and each verification annotation has a default message configuration. , for example, the message attribute value of @NotBlank
is set as shown below:
message = "{...}" The form specifies the name of the internationalization attribute, which will be replaced with the corresponding value according to the locale. For the definition of these internationalization attributes, please see
org.hibernate.validator in hibernate-validator
. ValidationMessages.properties and a series of international property definitions:
message="{propName}" to read the international properties, you can also directly set the value message="specific prompt information". If you do not explicitly set the message, use the previously mentioned
org.hibernate.validator.ValidationMessages.properties# Default configuration in ##.
Spring Boot Validation initially does not directly support reading Spring Boot’s own international configuration (configured through spring.messages), but needs to be configured in resources/ValidationMessages. Only the internationalization properties configured in properties will take effect, and the combination of Validation and Spring Boot's own internationalization configuration will be supported later in Spring Boot 2.6.
Next, combined with Spring Boot 2.5 and 2.6 versions, we will introduce how Spring Boot Validation integrates custom international verification prompt information.
Spring Boot 2.5.x
In Spring Boot 2.5.x version, Spring Boot Validation only supports reading the international code in the
resources/ValidationMessages.properties series of files by default. Internationalization attribute, and Chinese requires ASCII transcoding to display correctly as shown below:
Even the Spring Boot application also declares its own internationalization Configuration, but the Spring Boot Validation framework cannot read it
For example:
The international configuration of the Spring Boot application itself is as shown below, but the verification annotation message property is set to i18n/messages.properties The
"{propName}" cannot be read:
and you want the Spring Boot Validation framework and Spring Boot itself to use the same international configuration, you can configure it in the following way:
import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.validation.Validator; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * Spring Web验证器自定义国际化文件配置<br/> * 注:适用于Spring Boot 2.5.* * * @author luohq * @date 2022-05-21 */ @Configuration public class WebValidationConfig implements WebMvcConfigurer { /** * 国际化消息源 */ private MessageSource messageSource; public WebValidationConfig(MessageSource messageSource) { //注入Spring Boot国际化消息源(需通过spring.messages明确指定) this.messageSource = messageSource; } /** * 使用自定义LocalValidatorFactoryBean, * 设置Spring国际化消息源 */ @Bean @Override public Validator getValidator() { LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean(); //仅兼容Spring Boot spring.messages设置的国际化文件和原hibernate-validator的国际化文件 //不支持resource/ValidationMessages.properties系列 bean.setValidationMessageSource(this.messageSource); return bean; } }Note:
- After configuring through the above configuration class,
- Only compatible with the internationalization files set by Spring Boot spring.messages and the internationalization files of the original hibernate-validator
- The resource/ValidationMessages.properties series is no longer supported
- Spring Boot 2.6.x
I looked through the Release instructions of the Spring Boot framework on Github and found that it was mentioned in v2.6.0-M2 released on 2021-08-20 It is now supported to use its own internationalized MessageSource to parse verification prompt information. That is to say, Spring Boot 2.6.x and later supports the verification annotation message attribute to reference Spring Boot's own internationalized configuration.
Actually test the Spring Boot 2.6.x version and verify the annotation
:
- You can directly read the properties in the internationalization configuration set through
- spring.messages
(Chinese does not require ASCII transcoding after setting UTF-8 encoding),
Also supports reading the configuration in - resources
/
ValidationMessages.properties
(Chinese requires ASCII transcoding), and still supports the original Internationalization files for - hibernate-validator
.
And the read priority is from top to bottom, that is, the top one takes effect first.
The specific configuration and usage are shown in the figure below:
Spring Boot 2.6 Regarding the integration of Spring Boot Validation and MessageSource, the specific implementation details can be found in Release GitHub Pull Request #17530 mentioned:
The above is the detailed content of How to configure SpringBoot Validation prompt information internationalization. For more information, please follow other related articles on the PHP Chinese website!

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
