利用MessageSource实现国际化[I18N]
public class Example {private MessageSource messages;public void setMessages(MessageSource messages) {this.messages = messages;}public void execute() {String message = this.messages.getMessage("argument.required",new Object [] {"userDao"}, "Required", null);System.out.println(message);}}调用execute()方法的输出结果是...
The 'userDao' argument is required.
对于国际化(i18n),Spring中不同的MessageResource实现与JDK标准ResourceBundle中的locale解析规则一样。比如在上面例子中定义的messageSource bean,如果你想解析British (en-GB) locale的消息,那么需要创建format_en_GB.properties,exceptions_en_GB.properties和windows_en_GB.properties三个资源文件。
Locale解析通常由应用程序根据运行环境来指定。出于示例的目的,我们对将要处理的(British)消息手工指定locale参数值。
# in 'exceptions_en_GB.properties'argument.required=Ebagum lad, the '{0}' argument is required, I say, required.public static void main(final String[] args) {MessageSource resources = new ClassPathXmlApplicationContext("beans.xml");String message = resources.getMessage("argument.required",new Object [] {"userDao"}, "Required", Locale.UK);System.out.println(message);}上述程序运行时的输出结果是...
Ebagum lad, the 'userDao' argument is required, I say, required.
MessageSourceAware接口还能用于获取任何已定义的MessageSource引用。任何实现了MessageSourceAware接口的bean将在创建和配置的时候与MessageSource一同被注入。