如何在Spring Boot Service中正确使用text.properties配置文件?
问题:如何在Service中正确获取text.properties里的国际化消息?
现有代码片段
text.properties
exception.NO_ITEM_FOUND.message=Item with email {0} not found
NoSuchElementFoundException类
public class NoSuchElementFoundException extends RuntimeException { public NoSuchElementFoundException(String message) { super(message); } }
Service方法
public EmployeeDto findByEmail(String email) { return employeeRepository.findByEmail(email) .map(EmployeeDto::new) .orElseThrow(() -> new NoSuchElementFoundException(NO_ITEM_FOUND)); }
已编写的消息获取方法
private final MessageSource messageSource; private String getLocalMessage(String key, String... params){ return messageSource.getMessage(key, params, Locale.ENGLISH); }
目前不清楚如何根据用户语言(暂时仅使用默认语言)获取text.properties中的NO_ITEM_FOUND消息,不确定是否需要上述getLocalMessage方法以及如何在Service中使用它来正确获取配置的文本。
解决方法
你的getLocalMessage方法是可用的,只需按以下步骤在Service中正确调用即可:
确保MessageSource配置正确
先通过配置类让Spring加载你的text.properties文件:@Configuration public class MessageConfig { @Bean public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasenames("text"); // 对应text.properties文件,无需加后缀 messageSource.setDefaultEncoding("UTF-8"); return messageSource; } }在Service中注入并调用方法
通过构造方法注入MessageSource,然后在抛出异常时调用getLocalMessage,传入消息键和占位符参数:@Service public class EmployeeService { private final EmployeeRepository employeeRepository; private final MessageSource messageSource; // 构造注入 public EmployeeService(EmployeeRepository employeeRepository, MessageSource messageSource) { this.employeeRepository = employeeRepository; this.messageSource = messageSource; } private String getLocalMessage(String key, String... params){ return messageSource.getMessage(key, params, Locale.ENGLISH); // 暂时固定英文,后续可替换为用户实际Locale } public EmployeeDto findByEmail(String email) { return employeeRepository.findByEmail(email) .map(EmployeeDto::new) .orElseThrow(() -> new NoSuchElementFoundException( getLocalMessage("exception.NO_ITEM_FOUND.message", email) )); } }关键说明
- 调用
getLocalMessage时,第一个参数是text.properties里的完整键名exception.NO_ITEM_FOUND.message,第二个参数会自动替换消息中的{0}占位符,最终生成带具体邮箱的提示文本。 - 后续要支持多语言,只需新增对应语言的配置文件(比如
text_zh_CN.properties),再把Locale.ENGLISH替换为LocaleContextHolder.getLocale()即可自动适配用户语言。
- 调用
内容的提问来源于stack exchange,提问作者user19540291
相关产品推荐
相关产品推荐

