Sunday, 25 September 2016

Java Learner - Spring - Resource Bundle Message Source Example

Main Class
public class MainApp {
  public static void main(String[] args) {
     ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

     String text = context.getMessage("s.wish",
new Object[] {"saro", "stanes" },
                                        Locale.ENGLISH);

System.out.println("English... " + text);

String text2 = context.getMessage("s.wish",
new Object[] {"saro", "stanes" },
                                        Locale.FRANCE);

System.out.println("French... " + text2);
}
}

Beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/tx 
     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop 
     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<context:annotation-config/>
<context:component-scan base-package="com"/> 
   <!-- resource bundle -->
  <bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource ">
<property name="basename" value="resources/locale/messages"/>
</bean>
</beans>

messages_en_US.properties
s.wish=good morning, name : {0}, school : {1}

messages_fr_FR.properties
s.wish=bonjour, name : {0}, school : {1}

Output :
English... good morning, name : saro, school : stanes
French... bonjour, name : saro, school : stanes


     

No comments:

Post a Comment