1、国际化资源
使用IDEA创建资源组
2、编写配置
application.yml
增加国际化目录配置
增加国际化配置类 从请求头获取多语言关键字
/**
* 国际化配置
*
* @author Lion Li
*/
@Configuration
public class I18nConfig {
@Bean
public LocaleResolver localeResolver() {
return new I18nLocaleResolver();
}
/**
* 获取请求头国际化信息
*/
static class I18nLocaleResolver implements LocaleResolver {
@NotNull
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
String language = httpServletRequest.getHeader("content-language");
Locale locale = Locale.getDefault();
if (StrUtil.isNotBlank(language)) {
String[] split = language.split("_");
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(@NotNull HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
}
3、用法详解
在 Header 请求头 增加上下文语言参数 content-language
参数需与国际化配置文件后缀对应
如 zh_CN en_US 等
4、测试获取 code
对应国际化内容
编写测试类
/**
* 测试国际化
*
* @author Lion Li
*/
@RestController
@RequestMapping("/demo/i18n")
public class TestI18nController {
@Autowired
private MessageSource messageSource;
/**
* 通过code获取国际化内容
* code为 messages.properties 中的 key
*
* 测试使用 user.register.success
*/
@GetMapping()
public String get(String code) {
return messageSource.getMessage(code, new Object[]{}, LocaleContextHolder.getLocale());
}
}
测试接口
5.配置 Validator 校验 国际化
增加 validation 自动装配依赖
<!-- 自定义验证注解 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
编写 validation 配置类
/**
* 校验框架配置类
*
* @author Lion Li
*/
@Configuration
public class ValidatorConfig {
@Autowired
private MessageSource messageSource;
/**
* 配置校验框架 快速返回模式
*/
@Bean
public Validator validator() {
LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
// 设置上方配置的国际化源
factoryBean.setValidationMessageSource(messageSource);
// 设置使用 HibernateValidator 校验器
factoryBean.setProviderClass(HibernateValidator.class);
Properties properties = new Properties();
// 设置 快速异常返回
properties.setProperty("hibernate.validator.fail_fast", "true");
factoryBean.setValidationProperties(properties);
// 加载配置
factoryBean.afterPropertiesSet();
return factoryBean.getValidator();
}
}
编写全局异常处理 将所有的相关异常都进行拦截处理
/**
* 自定义验证异常
*/
@ExceptionHandler(BindException.class)
public AjaxResult<Void> handleBindException(BindException e) {
log.error(e.getMessage(), e);
String message = e.getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.joining(", "));
return AjaxResult.error(message);
}
/**
* 自定义验证异常
*/
@ExceptionHandler(ConstraintViolationException.class)
public AjaxResult<Void> constraintViolationException(ConstraintViolationException e) {
log.error(e.getMessage(), e);
String message = e.getConstraintViolations().stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.joining(", "));
return AjaxResult.error(message);
}
/**
* 自定义验证异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public AjaxResult<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
log.error(e.getMessage(), e);
String message = e.getBindingResult().getFieldError().getDefaultMessage();
return AjaxResult.error(message);
}
编写测试类
/**
* 测试国际化
*
* @author Lion Li
*/
@Validated
@Api(value = "测试国际化控制器", tags = {"测试国际化管理"})
@RestController
@RequestMapping("/demo/i18n")
public class TestI18nController {
/**
* Validator 校验国际化
* 不传值 分别查看异常返回
*
* 测试使用 not.null
*/
@ApiOperation("Validator 校验国际化")
@GetMapping("/test1")
public AjaxResult<Void> test1(@NotBlank(message = "{not.null}") String str) {
return AjaxResult.success(str);
}
/**
* Bean 校验国际化
* 不传值 分别查看异常返回
*
* 测试使用 not.null
*/
@ApiOperation("Bean 校验国际化")
@GetMapping("/test2")
public AjaxResult<TestI18nBo> test2(@Validated TestI18nBo bo) {
return AjaxResult.success(bo);
}
@Data
public static class TestI18nBo {
@NotBlank(message = "{not.null}")
private String name;
@NotNull(message = "{not.null}")
@Range(min = 0, max = 100, message = "{length.not.valid}")
private Integer age;
}
}
使用 Validator
框架校验 controller
参数返回国际化
controller
校验接口参数 需要在类增加 @Validated
注解
参数对应校验注解 使用 {code}
形式标注使用国际化处理
使用 Validator
框架校验 Bean
返回国际化
Bean
校验需要在接口校验 Bean
参数使用 @Validated
注解
Bean
内属性校验注解 使用 {code}
形式标注使用国际化处理