最近在整理springBoot国际化时,发现国际化没有生效,通过报错提示在
MessageTag -> doEndTag处打断点
最后发现messageSource并不是ResourceBundleMessageSource,而是DelegatingMessageSource代理对象,其内部代理的对象为null,可知springboot自动配置的ResourceBundleMessageSource没有生效。
springBoot启动时,会自动加载MessageSourceAutoConfiguration,同时我们需要注意的是MessageSourceAutoConfiguration上的@Conditional({MessageSourceAutoConfiguration.ResourceBundleCondition.class})注解,@Conditional注解为当满足里面所有Condition类的条件时执行,分析ResourceBundleCondition.class的getMatchOutcome方法
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { String basename = context.getEnvironment().getProperty("spring.messages.basename", "messages"); ConditionOutcome outcome = (ConditionOutcome)cache.get(basename); if (outcome == null) { outcome = this.getMatchOutcomeForBasename(context, basename); cache.put(basename, outcome); } return outcome; } private ConditionOutcome getMatchOutcomeForBasename(ConditionContext context, String basename) {
//默认目录默认名 Builder message = ConditionMessage.forCondition("ResourceBundle", new Object[0]); String[] var4 = StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(basename)); int var5 = var4.length; for(int var6 = 0; var6 < var5; ++var6) { String name = var4[var6];
//根据name,获取相关文件 Resource[] var8 = this.getResources(context.getClassLoader(), name); int var9 = var8.length; for(int var10 = 0; var10 < var9; ++var10) { Resource resource = var8[var10]; if (resource.exists()) { return ConditionOutcome.match(message.found("bundle").items(new Object[]{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 var5) {
return MessageSourceAutoConfiguration.NO_RESOURCES;
}
}
}
从上述代码可知,只有从classpath获取到默认文件夹默认前缀.properties文件,才可以获取到为true的ConditionOutcome,否则返回false