spring入门--applicationContext的国际化支持和让bean获取spring容器

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);


}

输出结果

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值