- Externalizing UI strings into external files other than code files and so easy-to-manage UI content.
- Supporting multiple languages.
- First, we must have some classes which includes string values shown on user interface:
- Then we must have an instance of an i18n utility class. This is generally one of the two in Java:
- java.util.ResourceBundle (doesn’t need spring dependency)
- org.springframework.context.support.ResourceBundleMessageSource (has multiple word externalization capability (which will be told later)).
- Then right click on the class and choose Source –> Externalize Strings. A window as below will be shown. Enter keys for strings into the right column. Keys will be started with class name as default. Keys must be unique on the system, so a predefined pattern should be applied (e.g. <class_name>.<type_id>.<description>)
- Click Next–> Finish and your strings will be changed as follows. And also Messages class and externalizer properties file will be created automatically (auto-comments on the right are markers for eclipse which means
- Now externalization is complete. But we want i18n, and we must support multiple languages. For this, define another properties file with location post-tag (e.g. “EN”, “FR”, “TR”, …), copy keys and fill values with new language and set locale of resource bundle in a proper place/action of your application (e.g. on settings window or login page):
|Multiple property files for each language|
|Messages_tr_TR.properties file content|
- As the last step, we want to encapsulate i18n utility class and also want to use a more capable i18n utility (e.g.
ResourceBundleMessageSource). For this, define a class as below:
- Finally, change “Messages.getString” statements into your new instance:
- You can also externalize parameterized strings using your class. Its usage will be as follows:
|Getting a parameterized string from i18n utility|
|Defining a parameterized string in property file|
Reference: Customized Internationalization (i18n) in Java – Step by Step from our JCG partner Cagdas Basaraner at the CodeBuild blog.