【Spring源码】MessageSource接口实现国际化

【Spring源码】MessageSource接口实现国际化


1. 准备配置文件

准备三个配置文件,内容如下:
在这里插入图片描述

2. java获取本地配置文件属性

    @Test
    public void javaPropertiesTest() throws IOException {
        // 读取messages.properties file属性
        getJavaPropertiesTest("messages.properties", "file");

        // 读取messages_en.properties file属性(英语)
        getJavaPropertiesTest("messages_en.properties", "file");

        // 读取messages_ja.properties file属性(日语)
        getJavaPropertiesTest("messages_ja.properties", "file");
    }

    private void getJavaPropertiesTest(String FileName, String key) throws IOException {
        InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(FileName);
        Properties properties = new Properties();
        properties.load(resourceAsStream);
        System.out.println("FileName=" + FileName + ", key = " + key +
                ", value = " + properties.get(key));
        printSplitRaw();
    }
    
    private void printSplitRaw() {
        System.out.println("------------------------------------------------");
    }

结果:
在这里插入图片描述

2. ResourceBundle国际化处理

   public void resourceBundleTest() {
        // 不设置国家和地区
        getResourceBundleTest("messages", Locale.getDefault(), "file");

        // 设置英语地区
        getResourceBundleTest("messages", Locale.ENGLISH, "file");

        // 设置日语地区
        getResourceBundleTest("messages", Locale.JAPANESE, "file");
    }

    private void getResourceBundleTest(String FileName, Locale locale, String key) {
        ResourceBundle enMessage = ResourceBundle.getBundle(FileName,
                locale, this.getClass().getClassLoader());
        System.out.println("FileName=" + FileName + ", locale=" + locale + ", key = " + key +
                ", value = " + enMessage.getString(key));
        printSplitRaw();
    }

    private void printSplitRaw() {
        System.out.println("------------------------------------------------");
    }

结果:
在这里插入图片描述

3. Spring boot获取本地配置文件配置

@SpringBootApplication
public class PaymentMain001 {
    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(PaymentMain001.class, args);
        System.out.println(applicationContext);

        String file = applicationContext.getMessage("file", null, Locale.ENGLISH);
        System.out.println(file);

        file = applicationContext.getMessage("file", null, Locale.JAPAN);
        System.out.println(file);

        file = applicationContext.getMessage("file", null, null);
        System.out.println(file);
    }
}

结果:
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值