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
相关推荐
道亦无名19 小时前
aiPbMgrSendAck
java·网络·数据库
发现你走远了19 小时前
Windows 下手动安装java JDK 21 并配置环境变量(详细记录)
java·开发语言·windows
心 -20 小时前
java八股文DI
java
NEXT0620 小时前
后端跑路了怎么办?前端工程师用 Mock.js 自救实录
前端·后端·程序员
泯泷20 小时前
提示工程的悖论:为什么与 AI 对话比你想象的更难
人工智能·后端·openai
黎雁·泠崖20 小时前
Java常用类核心详解(一):Math 类超细讲解
java·开发语言
大尚来也20 小时前
跨平台全局键盘监听实战:基于 JNativeHook 在 Java 中捕获 Linux 键盘事件
java·linux
追随者永远是胜利者20 小时前
(LeetCode-Hot100)15. 三数之和
java·算法·leetcode·职场和发展·go
懒惰成性的21 小时前
12.Java的异常
java·开发语言
装不满的克莱因瓶21 小时前
Java7新特性:try-with-resources写法
java·前端·javascript·jdk·新特性·jdk7