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
相关推荐
FYKJ_20106 分钟前
springboot校园兼职平台--附源码02041
java·javascript·spring boot·python·eclipse·django·php
书源丶1 小时前
三十六、File 类与 IO 流基础——文件操作的「第一步」
java
刀法如飞1 小时前
Go数组去重的20种实现方式,AI时代解决问题的不同思路
后端·算法·go
AI人工智能+电脑小能手1 小时前
【大白话说Java面试题】【Java基础篇】第30题:JDK动态代理和CGLIB动态代理有什么区别
java·开发语言·后端·面试·代理模式
swipe2 小时前
别再把 AI 聊天做成纯文本:从 agui 这个前后端项目,拆解“可感知工具调用”的流式 AI UI
后端·langchain·llm
GetcharZp2 小时前
GitHub 爆火!纯 Go 编写的文件同步神器 Syncthing,凭什么成为程序员的标配?
后端
hERS EOUS2 小时前
SpringBoot 使用 spring.profiles.active 来区分不同环境配置
spring boot·后端·spring
DFT计算杂谈2 小时前
wannier90 参数详解大全
java·前端·css·html·css3
LucianaiB2 小时前
我用飞书多维表做了一个 AI 活动推荐智能体:每天自动催我别错过截止日期!
后端
marsh02062 小时前
43 openclaw熔断与降级:保障系统在异常情况下的可用性
java·运维·网络·ai·编程·技术