栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot国际化

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot国际化

1.添加国际化文件

2.application.properties中添加配置参数
spring.messages.basename=i18n.common,i18n.login

 3.编写工具类I18nUtil
package com.example.demo;

import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Locale;

@Component
public class I18nUtil implements MessageSourceAware {

    private MessageSource messageSource;

    @Override
    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    public String get(String key, String locale){
        Locale realLocale = Locale.getDefault();
        if(!ObjectUtils.isEmpty(locale)){
            switch (locale){
                case "US":
                    realLocale = Locale.US;
                    break;
                case "CN":
                    realLocale = Locale.CHINA;
                    break;
            }
        }
        return messageSource.getMessage(key, null, realLocale);
    }
}
4.测试controller
package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private I18nUtil i18nUtil;

    @RequestMapping("i18n")
    public String i18n(String key, String locale){
        return i18nUtil.get(key, locale);
    }
}
5.测试
http://localhost:8000/user/i18n?key=order.tip&locale=US

http://localhost:8000/user/i18n?key=order.tip&locale=CN

6.另外方式
package com.example.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.Locale;

@SpringBootApplication
@MapperScan("com.example.demo.test")
public class DemoApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
        String message = context.getMessage("order.tip", null, Locale.US);
        System.out.println(message);
    }

}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/389744.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号