最近在整理springBoot國際化時,發現國際化沒有生效,經過報錯提示在spring
MessageTag -> doEndTag處打斷點springboot
最後發現messageSource並非ResourceBundleMessageSource,而是DelegatingMessageSource代理對象,其內部代理的對象爲null,可知springboot自動配置的ResourceBundleMessageSource沒有生效。ui
springBoot啓動時,會自動加載MessageSourceAutoConfiguration,同時咱們須要注意的是MessageSourceAutoConfiguration上的@Conditional({MessageSourceAutoConfiguration.ResourceBundleCondition.class})註解,@Conditional註解爲當知足裏面全部Condition類的條件時執行,分析ResourceBundleCondition.class的getMatchOutcome方法this
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,不然返回falsespa