SpringBoot Internationalization With Absolute Path MessageSource

This is a brief example of multilanguage MessageSource resource bundle loaded from absolute path outside the project classpath.

First Create Two Properties File

C:\Windows\Abe\i18n\example_en.properties

error.title=Your request cannot be processed
error.subtitle=Sorry, an error has occurred.

And:

C:\Windows\Abe\i18n\example_in.properties

error.title=Permintaan anda tidak bisa diproses
error.subtitle=Maaf, terjadi error.

Why in instead of id for indonesian? read here java.util.Locale::forLanguageTag and here https://tools.ietf.org/html/bcp47

Second, configure spring to load those file above

@Configuration
public class LocaleConfiguration implements WebMvcConfigurer {

    @Bean
    public ReloadableResourceBundleMessageSource messageSource() {
        ReloadableResourceBundleMessageSource rs = new ReloadableResourceBundleMessageSource();
        String multilangFile = "C:\\Windows\\Abe\\i18n\\example";
        rs.addBasenames("file:" + multilangFile);
        rs.setCacheSeconds(config.getMultilangCacheSeconds());
        log.debug("Setting basename for multilang file in: {}", rs.getBasenameSet());
        rs.setDefaultEncoding("UTF-8");
        rs.setUseCodeAsDefaultMessage(true);
        return rs;
    }
}

Put It On The Controller

@RestController
@RequestMapping("/test")
public class TestResource {

    @Autowired
    MessageSource messageSource;

    @GetMapping("/translate")
    public ResponseEntity<Map<String, String>> testTranslationA(@RequestParam(required=true, name="lang") String lang) {
        Map<String, String> translated = new HashMap<>();
        translated.put("error.title", 
                messageSource.getMessage("error.title", null, Locale.forLanguageTag(lang)));
        translated.put("error.subtitle", 
                messageSource.getMessage("error.subtitle", null, Locale.forLanguageTag(lang)));
        return new ResponseEntity<>(translated, HttpStatus.OK);
    }
}

Final Step: Test It

Open up terminal/shell

curl -X GET 'http://localhost:27072/test/translate?lang=id'

That should output:

{
    "error.subtitle": "Maaf, terjadi error.",
    "error.title": "Permintaan anda tidak bisa diproses"
}

Then try this:

curl -X GET 'http://localhost:27072/test/translate?lang=en'

If the output translated to english then mission accomplished.