介绍

客户端通过Accept-Language控制国际化显示。

messageSource

  • getMessage(String code, Object[] args, String defaultMessage, Locale locale)
  • getMessage(String code, Object[] args, Locale locale)
  • getMessage(MessageSourceResolvable resolvable, Locale locale)

使用

1、springboot自带国际化,不需要单独引入依赖。

2、在resource下新建 i18n/messages.properties

image.png

3、在启动配置文件增加以下内容

  • properties配置
# locale 国际化
spring.messages.basename=i18n/messages
spring.messages.encoding=UTF-8
spring.messages.cache-duration=-1
  • yml配置
# locale 国际化
spring:
    messages:
       basename: i18n/messages
       encoding: UTF-8
       cache-duration: -1

4、在使用的类中引入 MessageResource

@ControllerAdvice
public class GlobalExceptionHandler {
    @Autowired
    private MessageSource messageSource;
    
    private String getLocaleMessage(HttpServletRequest request, String code, Object[] msgArg) {
        Locale locale = RequestContextUtils.getLocale(request);
        if(locale == null){
            locale = Locale.US;
        }
        return messageSource.getMessage(code, msgArg, locale);
    }
}

5、在静态类中使用

public static BaseResponse success(HttpServletRequest request, String requestId, Object object){
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    
    messageSource.setCacheSeconds(-1);
    messageSource.setDefaultEncoding(StandardCharsets.UTF_8.name());
    messageSource.setBasenames("/i18n/messages");
    
    Locale locale = RequestContextUtils.getLocale(request);
    String code = ErrorCode.SUCCESS;
    String message = messageSource.getMessage(code, null, locale);
    BaseResponse res = new BaseResponse();
    res.setRequestId(requestId);
    res.setCode(code);
    res.setMessage(message);
    res.setData(object);
    return res;
}
public static String message(String code, Object... args){
    MessageSource messageSource = SpringUtils.getBean(MessageSource.class); 
    return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
}

风里有诗句
29 声望3 粉丝