简体   繁体   中英

Static strings localization issue in Java

Currently, I have a file called Messages which is a class with several static strings:

public class Messages {
    public static final String MESSAGE_1 = "Message one";
    public static final String MESSAGE_2 = "Message two";
    ...
}

What is the best way to refactor this implementation in order to support multiple languages? The name of the string should remain the same, but the value should change according to the locale string I pass. Not sure how to approach the implementation.

  1. create separate files under resources folder with name as messages_<locale>.properties for example messages_de_DE.properties for germany and so on.
  2. In these files put the key value pair as you put in any properties file with the text in the local of the filaname
  3. And create a bean like this.

     @Configuration class InternationalizationConfig { @Bean public LocaleResolver localeResolver() { SessionLocaleResolver slr = new SessionLocaleResolver(); slr.setDefaultLocale(Locale.GERMAN); return slr; } @Bean public ReloadableResourceBundleMessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:messages"); messageSource.setCacheSeconds(3600); return messageSource; } 

    }

Whereever you want to put locale specific string just autowire MessageSource

@Autowired
MessageSource messageSource;
 messageSource.getMessage(....)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM