Java REST接口返回JSON消息拼写缺失问题排查求助
Let’s break down the most likely causes for this issue and walk through how to fix them:
1. MessageFormat Parsing is Eating the Apostrophe
This is the most common culprit here. By default, ResourceBundleMessageSource uses MessageFormat to resolve messages—even when there are no placeholders in the text.
In MessageFormat, a single apostrophe (') acts as an escape character. So when your message is written as Person doesn't exist, MessageFormat interprets the ' as a marker to escape the following character (which doesn’t exist here), and removes it entirely, resulting in Person doesnt exist.
Fixes:
- Option 1: Escape the apostrophe in your
messages.propertiesfile using two apostrophes:NOT_FOUND_PERSON = Person doesn''t exist - Option 2: Disable unnecessary
MessageFormatparsing. SetalwaysUseMessageFormat=falseon yourResourceBundleMessageSourcebean to skip formatting for messages without placeholders:@Bean public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource source = new ResourceBundleMessageSource(); source.setBasenames("messages"); source.setDefaultEncoding("UTF-8"); // Critical for proper character handling source.setAlwaysUseMessageFormat(false); // Skips MessageFormat parsing return source; }
2. Incorrect Encoding Configuration
You were right to suspect UTF-8 encoding issues. The default encoding for ResourceBundle is ISO-8859-1, which can cause unexpected character handling even for symbols like apostrophes if your messages.properties file is saved in UTF-8 (which it should be for modern applications).
Fix:
Ensure you explicitly set the default encoding to UTF-8 on your ResourceBundleMessageSource bean (as shown in the code snippet above). Also, verify your IDE is saving the messages.properties file with UTF-8 encoding—most IDEs let you set this per file or project in the settings.
3. Verify Your Message Retrieval Code
Double-check how you’re fetching the message in your REST controller. If you’re using getMessage() methods that automatically apply MessageFormat (even when passing null for arguments), this will still trigger the apostrophe removal unless you’ve disabled the formatting flag.
For example, this call will still use MessageFormat by default:
messageSource.getMessage("NOT_FOUND_PERSON", null, Locale.getDefault());
Quick Test:
To confirm MessageFormat is the issue, temporarily hardcode the message in your controller. If it returns correctly (Person doesn't exist), then the problem is definitely in how the message is being loaded or parsed from the properties file.
内容的提问来源于stack exchange,提问作者Luke

