常见Spring相关工具报错-源码分析
- 1. Resouce Bundle 国际化 yml 配置不生效
1. Resouce Bundle 国际化 yml 配置不生效
1️⃣ 配置yml
2️⃣ 报错信息
2024-04-15 15:13:57.828 [http-nio-8090-exec-1] WARN o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - [doResolveHandlerMethodException,434] - Failure in @ExceptionHandler com.example.config.exception.GlobalExceptionHandle#handleI18nException(I18nException, HttpServletRequest) org.springframework.context.NoSuchMessageException: No message found under code 'global.not.null' for locale 'zh_tw'.
3️⃣ 源码分析 MessageSourceAutoConfiguration 配置类
在 getResources 中会获取 getResources(“classpath*:” + i18n/messages + “.properties”),但是缺少messages.properties属性文件
private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context, String basename) {
ConditionMessage.Builder message = ConditionMessage.forCondition("ResourceBundle");
for (String name : StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(basename))) {
for (Resource resource : getResources(context.getClassLoader(), name)) {
if (resource.exists()) {
return ConditionOutcome.match(message.found("bundle").items(resource));
}
}
}
return ConditionOutcome.noMatch(message.didNotFind("bundle with basename " + basename).atAll());
}
private Resource[] getResources(ClassLoader classLoader, String name) {
String target = name.replace('.', '/');
try {
return new PathMatchingResourcePatternResolver(classLoader)
.getResources("classpath*:" + target + ".properties");
}
catch (Exception ex) {
return NO_RESOURCES;
}
}
4️⃣ 解决:补充 messages.properties 文件