Spring Validation错误消息占位符无法正常转换问题咨询
Fixing @Size Message Placeholder Not Resolving to Max Value
Let's break down why your placeholders aren't working and how to fix this:
Why Your Current Attempts Failed
- Using
{1}gave you "1" instead of 30: Index-based placeholders don’t reliably map to themaxparameter in modern Bean Validation implementations. The index order might not align with your expectations, or your setup isn’t configured to resolve them correctly. - Using
{max}showed the literal "max" instead of 30: This means your message source isn’t properly binding the annotation’s parameter values to the named placeholders. This is usually a dependency or configuration issue.
Correct Solutions
1. Use Named Placeholders with Proper Validation Setup
First, keep your message.properties entry as:
user.validation.name.size=Your name must have less than {max} characters
Then ensure your setup is correct:
- If using Spring Boot, make sure you’ve included the
spring-boot-starter-validationdependency in yourpom.xmlorbuild.gradle. This pulls in the Bean Validation API and Hibernate Validator implementation, which natively supports named placeholders like{max}. - Verify your
MessageSourceis configured properly. Spring Boot automatically loadsmessage.propertiesfromsrc/main/resourcesby default, but if you’ve customized your message source setup, ensure it’s set to resolve validation messages correctly.
2. Fallback: Use SpEL Directly in the Annotation
For a quick fix without relying on the properties file, use Spring Expression Language (SpEL) to reference the max value directly in the annotation:
@Size(max = 30, message = "Your name must have less than ${max} characters") private String name;
This injects the 30 value directly into the error message.
3. Double-Check Message Key and Validation Trigger
Make sure there’s no typo in your message key (user.validation.name.size)—a misspelling could cause the system to fall back to a default message, leading to placeholder issues. Also, confirm that your validation logic is actually triggering the @Size check correctly.
内容的提问来源于stack exchange,提问作者Florent06
相关产品推荐
相关产品推荐

