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
相关推荐
大厂码农老A几秒前
你打的日志,正在拖垮你的系统:从P4小白到P7专家都是怎么打日志的?
java·前端·后端
摇滚侠2 分钟前
Spring Boot 3零基础教程,深度理解 Spring Boot 自动配置原理,笔记11
spring boot·笔记·后端
间彧16 分钟前
Spring Boot默认支持Logback的原因分析
后端
艾菜籽16 分钟前
Spring MVC入门补充2
java·spring·mvc
ezl1fe18 分钟前
第零篇:把 Agent 跑起来的最小闭环
人工智能·后端·agent
文心快码BaiduComate25 分钟前
文心快码Comate3.5S更新,用多智能体协同做个健康管理应用
前端·人工智能·后端
爆更小哇26 分钟前
统一功能处理
java·spring boot
程序员鱼皮28 分钟前
我造了个程序员练兵场,专治技术焦虑症!
java·计算机·程序员·编程·自学
我是天龙_绍32 分钟前
mybatis-plus 设置 数据库的字段自动填充
后端
Rust菜鸡33 分钟前
在你的Rust类型里生成TypeScript的bindings!
后端