spirn boot 国际化配置,消息化参数
1. 添加资源文件
messages_zh_CN.properties
# 注册登录
userid.is.null= 请输入用户名!
pwd.is.null= 请输入密码!
userid.error= 您输入的用户名格式不正确!
pwd.error= 您输入的密码格式不正确!
active.user.is.null= 您的用户名或密码输入错误!
# 用户管理
id.is.null= id不能为空!
addr.is.null= 地址不能为空!
sysuser.is.null= 用户不存在!
userstate.is.null= 请输入用户状态!
userstate.error= 用户状态输入错误,请输入{0}或{1}!
messages_en_US.properties
userid.is.null= please enter user name!
pwd.is.null= Please enter your password!
userid.error= The user name you entered is not in the correct format!
pwd.error= The password you entered is not in the correct format!
active.user.is.null= Your username or password was entered incorrectly!
# 用户管理
id.is.null= Id cannot be empty!
addr.is.null= The address cannot be empty!
sysuser.is.null= User does not exist!
userstate.error= User status entry error, please enter {0} or {1}!
2. 添加配置类
@Configuration
public class InitialConfig {
/** 国际化文件路径 */
@Value("${spring.messages.basename}")
public String basename;
/**
* 用于解析消息的策略接口,支持这些消息的参数化和国际化。
*
* @return
*/
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename(basename);
return messageSource;
}
}
3.校验类中使用
/**
* 校验工具类
*
* @author colg
*/
@Component
public class CheckUtil {
private static MessageSource source;
/**
* 在Spring里,静态变量/类变量不是对象的属性,而是一个类的属性,不能用@Autowired一个静态变量(对象),使之成为一个SpringBean。<br />
*
* 只能通过setter方法注入,并把类注解成为组件
*
*
* @param source
*/
@Autowired
public void init(MessageSource source) {
CheckUtil.source = source;
}
/**
* 抛出校验错误异常
*
* @param msgKey
* @param args
*/
private static void fail(String msgKey, Object... args) {
// 消息的参数化和国际化配置
Locale locale = LocaleContextHolder.getLocale();
msgKey = source.getMessage(msgKey, args, locale);
throw new CheckException(msgKey);
}
}
4. 展示效果