Spring boot application and MessageSource
Can you create a messages package in resources and try this Bean implementation in your configuration file:
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
messageSource.setCacheSeconds(10); //reload messages every 10 seconds
return messageSource;
}
Additionally, I suggest you to use @Configuration annotated configuration classes instead of xml files to be adapted perfectly to Spring Boot concept.
I had the same issue on springboot app. I have tested one of the below options:
If you prefer to modify application.properties
file then add this line spring.messages.basename=messages
where messages is the prefix of the file containing your messages. with this u don't have to setup a messagesource
bean yourself.
or
i had to give the MessageResource
bean a name and autowire it using the name given during initialization, otherwise DelegatingMessageSource
was being injected and it wasn't resolving to any message source.
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver localResolver=new SessionLocaleResolver();
localResolver.setDefaultLocale(Locale.US);
return localResolver;
}
@Bean(name = "messageResourceSB")
public MessageSource messageResource() {
ResourceBundleMessageSource messageBundleResrc=new ResourceBundleMessageSource();
messageBundleResrc.setBasename("msg.message");
return messageBundleResrc;
}
}
then autowire the bean with the name u expect
@RestController
public class Internationalization {
@Autowired
@Qualifier("messageResourceSB")
MessageSource messageSource;
@GetMapping(path = "/sayHelloIntern")
public String sayHello(@RequestHeader(name="Accept-Language",required = false) Locale locale) {
return messageSource.getMessage("message.greeting", null, locale);
}
}
You can also configure through application.properties
below i18n.messages points to messages files under classpath folder i18n
spring.messages.basename=i18n.messages
Refer SpringBoot doc click here
The issue was my Eclipse encoding configuration, which I haven't managed to fix yet.
After debugging Spring's code (ReloadableResourceBundleMessageSource.java
) I could see my key=value
property loaded, but with 3 space characters before each character (e.g. t e s t = T h i s i s a d e m o a p p !
).
On another PC the same demo application works fine.