springboot自動配置國際化失效分析


最近在整理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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM