介绍
客户端通过 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
3、在启动配置文件减少以下内容
- properties 配置
# locale 国际化
spring.messages.basename=i18n/messages
spring.messages.encoding=UTF-8
- yml 配置
# locale 国际化
spring:
messages:
basename: i18n/messages
encoding: UTF-8
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;
}