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
相关推荐
花间相见15 分钟前
【Java基础面试题】—— 核心知识点面试题(含答案):语法+集合+JVM+设计模式+算法
java·jvm·设计模式
钟智强19 分钟前
从2.7GB到481MB:我的Docker Compose优化实战,以及为什么不能全信AI
后端·docker
会飞De琥珀21 分钟前
java工具类,字符串转时间
java·开发语言
曹牧43 分钟前
JSON 数组的正确使用方式
java·服务器·前端
LINgZone244 分钟前
深入解析:Cglib与JDK动态代理的实现原理、区别及性能对比
java·开发语言
华科易迅1 小时前
Spring JDBC
java·后端·spring
云烟成雨TD1 小时前
Spring AI 1.x 系列【17】函数型工具开发与使用
java·人工智能·spring
小村儿1 小时前
一起吃透 Claude Code,告别 AI 编程迷茫
前端·后端·ai编程
程序员大飞哥1 小时前
云控SLA的数学:250ms端到端延迟预算怎么分配给传输层
后端
云烟成雨TD1 小时前
Spring AI 1.x 系列【15】AI Agent 基石:Tool Calling 标准与 Spring AI 集成
java·人工智能·spring