Issue
I have scheduler. Each 5 sec I get some items from DB and send push notifications to android. But Text in this notifications in Rusian language. In feature we wand support different languages, and now i tried create some templates. I have property file for message templates: messages_ru_RU.properties
and I have string in this file: notification.message=%s. На сумму: %s. Карта: %s
I need load this String from property and repalse %s
to my values. Now I create config an service:
@Configuration
public class LocaleConfig {
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
Locale defaultLocale = new Locale("ru");
slr.setDefaultLocale(defaultLocale);
return slr;
}
@Bean
public ReloadableResourceBundleMessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
messageSource.setCacheSeconds(3600); //refresh cache once per hour
return messageSource;
}
}
and service:
@Component
public class MessageByLocaleServiceDefault implements MessageByLocaleService {
private final MessageSource messageSource;
@Autowired
public MessageByLocaleServiceDefault(MessageSource messageSource) {
this.messageSource = messageSource;
}
@Override
public String getMessage(String id) {
Locale locale = LocaleContextHolder.getLocale();
return messageSource.getMessage(id, null, locale);
}
}
and I try load string from property like this:
String messagePlaceholder = messageByLocaleService.getMessage("notification.message");
But I see this:
My question - how can I load russian(cyrillic, utf-8) text from message.properties in spring boot?
My property file saved in utf-8 encoding.
Solution
Make sure to also set the MessageSource
encoding properly by configuring the setDefaultEncoding()
property:
@Bean
public ReloadableResourceBundleMessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
messageSource.setCacheSeconds(3600);
messageSource.setDefaultEncoding("UTF-8"); // Add this
return messageSource;
}
According to the API documentation, the default is ISO-8859-1:
Default is none, using the
java.util.Properties
default encoding: ISO-8859-1.
Also, be aware that SessionLocaleResolver
only works for user sessions. If you're going to use the MessageSource
in combination with a scheduled task, it's not going to work.
Answered By - g00glen00b
Answer Checked By - Mildred Charles (JavaFixing Admin)