Java文件中的Spring国际化错误

我正在尝试从.java文件从messages_en.properties发送带有模板的SMS消息。

我的WebMvcConfig文件是:

    @Bean(name = "messageSource")
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("i18n/messages");
        messageSource.setDefaultEncoding(StandardCharsets.UTF_8.toString());
        return messageSource;
    }

我的.java文件是:

content = messageSource.getMessage("delivery.otp.sms.template", new Object[] {"123456"}, LocaleContextHolder.getLocale())

而我的文件在main / resources / i18n / messages_en.properties中

delivery.otp.sms.template=Your OTP is {0}.

但是我得到了错误:

在代码“ delivery.otp.sms.template”下找不到区域设置“ en_US”的消息

请帮忙。谢谢。

评论
  • 祈~祷
    祈~祷 回复

    Just add classpath: in your basename. So the final code would be like below:

    @Bean(name = "messageSource")
        public MessageSource messageSource() {
            ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
            messageSource.setBasename("classpath:i18n/messages");
            messageSource.setDefaultEncoding(StandardCharsets.UTF_8.toString());
            return messageSource;
        }
    

    The reason is that if you do not add classpath: it will consider the give path as a abosolute path but since we have relative path (main/resources/i18n/messages_en.properties) here, its better to add classpath:so, spring will look from the direcotry where jar is running.