You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 the max parameter 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-validation dependency in your pom.xml or build.gradle. This pulls in the Bean Validation API and Hibernate Validator implementation, which natively supports named placeholders like {max}.
  • Verify your MessageSource is configured properly. Spring Boot automatically loads message.properties from src/main/resources by 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:24:56