05点睛Spring4.1-国际化

5.1 ReloadableResourceBundleMessageSource

  • 使用ReloadableResourceBundleMessageSource可获得不同语言的配置
  • 此处是全局配置,适合用@Bean声明

5.2 示例

5.2.1 新建英文messagesmessages_en_US.properties

wisely.name = wyf
wisely.age = 32

5.2.2 新建中文messagesmessages_zh_CN.properties

wisely.name = \u6C6A\u4E91\u98DE
wisely.age = 3-10-2

5.2.3 配置ReloadableResourceBundleMessageSource

package com.wisely.i18n;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;

@Configuration
public class I18NConfig {
    @Bean
    public static ReloadableResourceBundleMessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource= new ReloadableResourceBundleMessageSource();
        String[] resources = {"classpath:com/wisely/i18n/messages"};
        messageSource.setBasenames(resources);
        messageSource.setCacheSeconds(1);
        return messageSource;
    }

}

5.2.4 测试

package com.wisely.i18n;

import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class Main {
    @Autowired
    MessageSource messageSource;

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext("com.wisely.i18n");
        String nameEn = context.getMessage("wisely.name",null, Locale.US);
        String nameCn = context.getMessage("wisely.name",null, Locale.CHINA);
        System.out.println("nameEN="+nameEn);
        System.out.println("nameCN="+nameCn);

        Main main = context.getBean(Main.class);
        main.showAgeInfo(context);

        context.close();
    }

    public void showAgeInfo(AnnotationConfigApplicationContext context){
        String ageEn = context.getMessage("wisely.age",null, Locale.US);
        String ageCn = context.getMessage("wisely.age",null, Locale.CHINA);
        System.out.println("nameEN="+ageEn);
        System.out.println("nameCN="+ageCn);
    }
}

输出结果

nameEN=wyf
nameCN=汪云飞
nameEN=32
nameCN=3-10-2

新书推荐《JavaEE开发的颠覆者: Spring Boot实战》,涵盖Spring 4.x、Spring MVC 4.x、Spring Boot企业开发实战。

 

京东地址:http://item.jd.com/11894632.html

当当地址:http://product.dangdang.com/23926195.html

亚马逊地址:http://www.amazon.cn/图书/dp/B01D5ZBFUK/ref=zg_bsnr_663834051_6 

淘宝地址:https://item.taobao.com/item.htm?id=528426235744&ns=1&abbucket=8#detail

 

 

 

或自己在京东、淘宝、亚马逊、当当、互动出版社搜索自选。

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值