ApplicationContext接口继承MessageSource接口,因此具备国际化功能。下面是MessageSource接口定义的三个国际化方法。
》String getMessage(String code, Object[] args, Locale loc)
》String getMessage(String code, Object[] args, String default, Locale loc)
》String getMessage(MessageSourceResolvable resolvable, Locale locale)
当程序创建ApplicationContext容器时,Spring自动查找在配置文件中名为 messageSource 的 Bean 实例,一旦找到这个Bean实例,上诉3个方法的调用被委托给该MessageSource Bean。一般会将massageSource配置为org.springframework.context.support.ResourceBundleMessageSource类,所以需要在配置文件中加上这段
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>message</value>
<!--如果有多个资源文件,全部列在此处-->
</list>
</property>
</bean>
配置属性的value为massage,那么你的资源文件应该命名为message_en_US.properties或message_zh_CN.properties
第一个是美式文件的格式,第二个为简体中文的格式。
如果资源文件中含有非西欧文字,应该用native2ascii工具(windows下是这个)转化一下,不然会出错。
下面为主程序
package bean;
import java.util.Locale;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class springtest {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
String hello=context.getMessage("hello", new String[] {"孙悟空"},Locale.getDefault(Locale.Category.FORMAT));
System.out.println(hello);
}
输出结果