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
相关推荐
それども4 分钟前
Comparator.comparing 和 拆箱问题
java·jvm
星晨羽1 小时前
西门子机床opc ua协议实现变量读写及NC文件上传下载
java·spring boot
码事漫谈2 小时前
兵临城下:DeepSeek-V4 的技术突围与算力“成人礼”
后端
无巧不成书02182 小时前
零基础Java网络编程全解:从核心概念到Socket实战,一文打通Java网络通信
java·开发语言·网络
三水不滴2 小时前
SpringAI + SpringDoc + Knife4j 构建企业级智能问卷系统
经验分享·spring boot·笔记·后端·spring
aq55356002 小时前
Workstation神技:一键克隆调试环境
java·开发语言
玖玖passion3 小时前
Windows 上部署 Hermes Agent 完整指南 - 让你的 AI 助手在 WSL2 中跑起来
前端·后端·github
今天你TLE了吗3 小时前
LLM到Agent&RAG——AI知识点概述 第六章:Function Call函数调用
java·人工智能·学习·语言模型·大模型
Rcnhtin3 小时前
RocketMQ
java·linux·rocketmq