为此,您可以创建自己的自定义消息源。
就像是:
public class SpecialMessageSource extends ReloadableResourceBundleMessageSource {
@Override
protected MessageFormat resolveCode(String code, Locale locale) {
MessageFormat result = super.resolveCode(code, locale);
if (result.getPattern().isEmpty() && locale == Locale.CHINESE) {
return super.resolveCode(code, Locale.ENGLISH);
}
return result;
}
@Override
protected String resolveCodeWithoutArguments(String code, Locale locale) {
String result= super.resolveCodeWithoutArguments(code, locale);
if ((result == null || result.isEmpty()) && locale == Locale.CHINESE) {
return super.resolveCodeWithoutArguments(code, Locale.ENGLISH);
}
return result;
}
}
并在 spring xml 中将此 messageSource bean 配置为
<bean id="messageSource" class="SpecialMessageSource">
.....
</bean>
现在要获得解决标签,您将调用 MessageSource's
以下任一方法
String getMessage(String code, Object[] args, Locale locale);
String getMessage(String code, Object[] args, String defaultMessage, Locale locale);
resolveCode()
当您的消息标签具有参数并且您通过args
如下参数传递这些参数并调用时
invalid.number= {0} is Invalid
将调用messageSource.getMessage("INVALID_NUMBER", new Object[]{2d}, locale)
resolveCodeWithoutArguments()
当您的消息标签没有参数并且您将args
参数传递为 null
validation.success = Validation Success
并且您调用时将被调用messageSource.getMessage("INVALID_NUMBER", null, locale)