SpringBoot国际化配置(i8n配置)未生效(完美解决)

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

从上述代码发现,他需要读取后缀为.properties才可以获取到为true的ConditionOutcome,否则返回false

参考文章:https://www.cnblogs.com/jaxlove-it/p/10613040.html

猜你喜欢

转载自blog.csdn.net/weixin_43409994/article/details/107106395