Solving Spring Message Resource Bundle UTF-8 Problem

26-01-2015

To solve Spring resource bundle UTF-8 problem, you should add specific message source bundle bean as follows:
<bean id="messageSource"
      class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="classpath:messages" />
    <property name="fallbackToSystemLocale" value="true" />
    <property name="fileEncodings" value="UTF-8" />
    <property name="defaultEncoding" value="UTF-8" />
    <property name="cacheSeconds" value="3600"/>
</bean>

Also, you should save .properties file(s) as UTF-8 encoding.

classpath:messages points to properties files in maven resources folder which start with messages prefix

Note: In contrast to ResourceBundleMessageSource, ReloadableResourceBundleMessageSource class supports reloading of properties files through the cacheSeconds settings.

Note: Since application servers typically cache all files loaded from the classpath, it is necessary to store resources somewhere else (for example, in the "WEB-INF" directory of a web app). Otherwise changes of files in the classpath will not be reflected in the application.

If you are using ResourceBundleMessageSource, you have to omit classpath: prefix as follows:
<bean id="messageSource"
      class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="messages" />
    <property name="defaultEncoding" value="UTF-8" />
    <property name="cacheSeconds" value="3600"/>
</bean>

© 2019 All rights reserved. Codesenior.COM