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
相关推荐
钱栈up8 小时前
烧结趋势页台车速度曲线凭空消失:一次\\\"去重\\\"误杀的配置修复
后端·测试
刘小灰14 小时前
返璞归真,我开始更新博客了
前端·后端
一条Go15 小时前
巡检报告:把一次性排障变成可复跑的任务
后端·github
一条Go15 小时前
SQL 实验室:只读靠两把锁,DDL 靠模板
后端·github
一条Go15 小时前
维护窗口与升级策略:静默和升级怎么共存
后端·github
一条Go15 小时前
应用商店:版本、发布与部署为什么必须拆成三个阶段
后端·github
郝学胜-神的一滴15 小时前
Effective STL 条款15:注意字符串实现上的差异
java·开发语言·数据结构·c++·算法·visualstudio
sharemylove15 小时前
Java学习笔记 —— 面向对象专题
java·开发语言·笔记·学习·课程设计
京东云开发者16 小时前
一份数据,两种协议:京东云存储打通文件与对象
后端
代码民工正电荷16 小时前
JAVA学习基础(一)
java·开发语言·学习