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
相关推荐
利威尔xu10 分钟前
2026-11-24-Go限流器实战
后端·golang
CoderYanger1 小时前
Java EE 进阶:12.Spring AOP(第一弹)
java·开发语言·spring boot·后端·spring·java-ee·交互
H H.2 小时前
Java笔记:String字符串
java·开发语言·经验分享·笔记·其他
Rain的Java大神之路2 小时前
Spring AI 还是 LangChain4j?2026 年 Java 接入大模型,我把这笔「架构赌注」的账算清楚了
java·后端·ai编程
用户112936112192 小时前
注释掉的接口为什么还能访问?没有 Git 也能证明改动有没有进产物
java
Csvn2 小时前
Nginx 高可用网关:VIP 切换、proxy_protocol 与 SNI 分流实战
后端·nginx
Gopher_HBo2 小时前
跟着一次导出,走完 runtime/pprof:从一张工单到一份文件
后端
sharemylove2 小时前
Java 异常处理 学习笔记
java·开发语言·经验分享·笔记·学习
用户69371750013842 小时前
大模型蒸馏到底在蒸什么?一篇文章搞懂知识蒸馏概念
前端·后端·github
CRZZX3 小时前
三引擎 Agent 方案设计与性能测试总结
后端·架构