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
相关推荐
杨DaB15 分钟前
【SpringBoot】Swagger 接口工具
java·spring boot·后端·restful·swagger
YA33316 分钟前
java基础(九)sql基础及索引
java·开发语言·sql
why技术27 分钟前
也是震惊到我了!家里有密码锁的注意了,这真不是 BUG,是 feature。
后端·面试
桦说编程35 分钟前
方法一定要有返回值 \ o /
java·后端·函数式编程
小李是个程序1 小时前
登录与登录校验:Web安全核心解析
java·spring·web安全·jwt·cookie
David爱编程1 小时前
Java 创建线程的4种姿势,哪种才是企业级项目的最佳实践?
java·后端
ciku1 小时前
Spring AI 集成阿里云百炼平台
人工智能·spring·阿里云
hrrrrb2 小时前
【Java Web 快速入门】十一、Spring Boot 原理
java·前端·spring boot
Java微观世界2 小时前
Object核心类深度剖析
java·后端
MrSYJ2 小时前
为什么HttpSecurity会初始化创建两次
java·后端·程序员