java实现多语言&spring实现多语言

108 阅读2分钟

背景

  • 随着产品或者项目的国际化,IT项目需要支持多语言来更好的支持业务的发展,java在多语言方面有着较好的支持,我们今天来看看通过原生的java和spring两种方式来实现国际化
  • 多语言一般简称i18n,为什么这么叫?是因为internationalization首末字母之间有18个字母

java实现多语言

  • java使用ResourceBundle来绑定资源
  • 实现代码如下
ResourceBundle messages = ResourceBundle.getBundle("messages");
String string = messages.getString("all.toatal.sum.tip");
System.out.println(string);
  • 截图如下

image.png

image.png

  • 如果resource下面有多级目录,例如有一个i18n的话,则使用的时候可以ResourceBundle.getBundle("i18n.messages");来获取

spring实现多语言

  • spring实现多语言的方式为MessageSource接口实现,实现类可以参考ResourceBundleMessageSource
  • 以下代码展示一下具体的实现方式,首先需要在resource目录下面创建多语言的文件
  • MessagesUtil类封装设置消息的方法
package org.example.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Locale;

@Component
@Slf4j
public class MessagesUtil implements InitializingBean {

    @Resource
    private MessageSource messageSource;



    public String  getMessage(String code){
         String  message = code;
        try {
            message = messageSource.getMessage(code, null, LocaleContextHolder.getLocale());
        } catch (NoSuchMessageException e) {
            log.info("获取多语言失败",e);
        }
        return  message;
    }

    public String getMessage(String code,Object[] params){
        String  message = code;
        try {
            message = messageSource.getMessage(code, params, LocaleContextHolder.getLocale());
        } catch (NoSuchMessageException e) {
            log.info("获取多语言失败",e);
        }
        return  message;
    }


    public String getMessage(String code,Object[] params,String defaultMessage){
        String  message = code;
        try {
            message = messageSource.getMessage(code, params, defaultMessage,LocaleContextHolder.getLocale());
        } catch (NoSuchMessageException e) {
            log.info("获取多语言失败",e);
        }
        return  message;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        //默认设置为中文
       LocaleContextHolder.setDefaultLocale(Locale.CHINA);
    }
}
  • 定义异常类BizException
package org.example.exception;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Data
public class BizException extends RuntimeException{

    public String code;

    public String  message;

    public Object[] params;

    public BizException(){

    }
    public BizException(String code,String message){
        super(message);
        this.code = code;
    }

    public BizException(String code,Object[] params){
        super(code);
        this.code = code;
        this.params = params;
    }
}
  • 定义接口返回类JsonResponse
package org.example.response;

import lombok.Data;

import java.io.Serializable;

@Data
public class JsonResponse<T> implements Serializable {

    private String code;

    private String message;
    private T data;

    public JsonResponse(String code,String message){
        this.code =  code;
        this.message = message;
    }

    public JsonResponse(String code,String message,T data){
        this.code =  code;
        this.message = message;
        this.data = data;
    }

    public  static <T> JsonResponse<T>  success(String code,String message,T data){
        org.example.response.JsonResponse<T> tJsonResponse = new JsonResponse<>(code, message, data);
        return  tJsonResponse;
    }

    public  static <T> JsonResponse<T>  fail(String code,String message){
        org.example.response.JsonResponse<T> tJsonResponse = new JsonResponse<>(code, message);
        return  tJsonResponse;
    }
}
  • 定义全局异常捕获类ExceptionHandler
package org.example.exception;

import lombok.extern.slf4j.Slf4j;
import org.example.config.MessagesUtil;
import org.example.response.JsonResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.annotation.Resource;
@Slf4j
@RestControllerAdvice
public class ExceptionHandler {
    @Resource
    private  MessagesUtil messagesUtil;
    @org.springframework.web.bind.annotation.ExceptionHandler(value = BizException.class)
    public JsonResponse  bizException(BizException e){
        String message = messagesUtil.getMessage(e.getCode(),e.params,e.getCode());
        log.error("错误异常BizException",e);
       return JsonResponse.fail(e.getCode(),message);
    }
}
  • yaml配置 image.png
spring:
  messages:
    basename: i18n/messages
    encoding: UTF-8
  • 测试类TestController
package org.example.controller;

import org.example.exception.BizException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class TestController {
    @GetMapping("/testi18n")
    public void test(){
        throw  new BizException("all.toatal.sum.tip",new Object[]{",我是认真的"});
    }
}

后记

  • 以上为java语言实现多语言的两种方式,可以在这两种方式上扩展自己项目实际需要的多语言的方式