Spring i18n国际化

从源码MessageSource的三个实现出发实战spring·i18n国际化 - 简熵 - 博客园

java 复制代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;

import java.util.Locale;
import java.util.ResourceBundle;

@SpringBootApplication
public class HelloWorldSpringbootApplication {
    // ReloadableResourceBundleMessageSource可以加载指定项目以外的国际化文件
    private static String zhPath =
            "file:D:/temp/content";
    public static void main(String[] args) {
        // SpringApplication.run(HelloWorldSpringbootApplication.class, args);
        getSpringContent();
    }

    @Bean
    public ReloadableResourceBundleMessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasenames(zhPath, "classpath:content");
        return messageSource;
    }

    public static void getSpringContent() {
        AnnotationConfigApplicationContext ctx =
                new AnnotationConfigApplicationContext(HelloWorldSpringbootApplication.class);
        MessageSource source = ctx.getBean(MessageSource.class);
        Locale localeZh = new Locale("zh","CN");
        String hello = source.getMessage("hello", null, localeZh);
        System.out.println("hello = " + hello);
    }

    public static void getContent() {
        Locale localeEn = new Locale("en","US");
        Locale localeZh = new Locale("zh","CN");
        ResourceBundle res = ResourceBundle.getBundle("content", localeZh);
        String hello = res.getString("hello");
        System.out.println("hello = " + hello);
    }
}

再加三个文件:

复制代码
content.properties
java 复制代码
hello=123
复制代码
content_en_US.properties
java 复制代码
hello=hello_world

content_zh_CN.properties

java 复制代码
hello=456
相关推荐
Lovely_Ruby2 分钟前
前端er Go-Frame 的学习笔记:实现 to-do 功能(一)
前端·后端
喵个咪5 分钟前
初学者导引:在 Go-Kratos 中用 go-crud 实现 Ent ORM CRUD 操作
后端·go
开源之眼5 分钟前
github star 较多的Java双亲委派机制【类加载的核心内容加星】
java
计算机毕设匠心工作室6 分钟前
【python大数据毕设实战】全国健康老龄化数据分析系统、Hadoop、计算机毕业设计、包括数据爬取、数据分析、数据可视化、机器学习
后端·python
编程火箭车7 分钟前
【Java SE 基础学习打卡】19 运算符(中)
java·java入门·运算符·编程基础·赋值运算符·复合赋值·自增自减
是一个Bug7 分钟前
Spring事件监听器源码深度解析
java·数据库·spring
蜂蜜黄油呀土豆12 分钟前
ThreadLocal 深度解析:它解决了什么、原理是什么、如何正确使用(含代码与实战建议)
java·并发编程·内存泄漏·threadlocal
v***870415 分钟前
Spring Boot实现多数据源连接和切换
spring boot·后端·oracle
哈哈哈笑什么15 分钟前
企业级追踪业务数据变动的通用组件
后端
毕设源码-郭学长16 分钟前
【开题答辩全过程】以 高校教室管理系统为例,包含答辩的问题和答案
java·spring boot