Java Reference
In-Depth Information
application context to detect it. You have to specify the base name of the resource bundles for
ResourceBundleMessageSource .
<beans ...>
...
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
<value>messages</value>
</property>
</bean>
</beans>
For this MessageSource definition, if you look up a text message for the United States locale, whose
preferred language is English, the resource bundle messages_en_US.properties , which matches both the
language and country, will be considered first. If there's no such resource bundle, or the message can't
be found, the one messages_en.properties that matches the language only will be considered. If this
resource bundle still can't be found, the default messages.properties for all locales will be finally chosen.
For more information on resource bundle loading, you can refer to the javadoc of the
java.util.ResourceBundle class.
Now you can ask the application context to resolve a message by the getMessage() method. The first
argument is the key corresponding to the message, and the third is the target locale.
package com.apress.springenterpriserecipes.shop;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
...
public class Main {
public static void main(String[] args) throws Exception {
ApplicationContext context =
new FileSystemXmlApplicationContext("beans.xml");
...
String alert = context.getMessage("alert.checkout", null, Locale.US);
System.out.println(alert);
}
}
The second argument of the getMessage() method is an array of message parameters. In the text
message, you can define multiple parameters by index:
alert.checkout=A shopping cart costing {0} dollars has been checked out at {1}.
You have to pass in an object array to fill in the message parameters. The elements in this array will
be converted into strings before filling in the parameters.
package com.apress.springenterpriserecipes.shop;
...
public class Main {
public static void main(String[] args) throws Exception {
...
Search WWH ::




Custom Search