If you want to access i18n resources bundles for different locales into your java source code, then that java class must implement MessageSourceAware interface. After implementing MessageSourceAware interface, spring context will automatically inject the MessageSource reference into the class via setMessageSource(MessageSource messageSource) setter method which your class need to implement.
How to access MessageSource in spring bean
As mentioned, make your bean class MessageSourceAware as given way.
| packagecom.howtodoinjava.demo.controller;importorg.springframework.context.MessageSource;importorg.springframework.context.MessageSourceAware;@ControllerpublicclassEmployeeController implementsMessageSourceAware{    privateMessageSource messageSource;     publicvoidsetMessageSource(MessageSource messageSource) {        this.messageSource = messageSource;    }    publicvoidreadLocaleSpecificMessage()    {    String englishMessage = messageSource.getMessage("first.name", null, Locale.US);         System.out.println("First name label in English : "+ englishMessage);         String chineseMessage = messageSource.getMessage("first.name", null, Locale.SIMPLIFIED_CHINESE);                 System.out.println("First name label in Chinese : "+ chineseMessage);    }} | 
Now there are two properties files in “resources” folder in web application. (Files should be in classpath in runtime).
messages_en_US.properties and messages_zh_CN.properties
| #messages_en_US.propertiesfirst.name=FirstName in English#messages_zh_CN.propertiesfirst.name=FirstName in Chinese | 
Now test if we are able to load locale specific properties.
| packagespringmvcexample;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importcom.howtodoinjava.demo.controller.EmployeeController;publicclassTestSpringContext {    @SuppressWarnings("resource")    publicstaticvoidmain(String[] args)     {        ApplicationContext context = newClassPathXmlApplicationContext( newString[] { "/spring-servlet.xml"});        EmployeeController controller = (EmployeeController) context.getBean(EmployeeController.class);                controller.readLocaleSpecificMessage();    }}Output:First name label in English : FirstName in EnglishFirst name label in Chinese : FirstName in Chinese | 
Clearly, we are able to access resources in locale specific manner inside java bean.
 
No comments:
Post a Comment