i18n 适用于 Thymeleaf 但不适用于 MessageSource

i18n works with Thymeleaf but not with MessageSource

我正在使用 Spring MVC+T​​hymeleaf,当我尝试从 MessageSource 获取消息时出现以下异常:NoSuchMessageException

我的配置:

@Bean(name="messageSource")
    public MessageSource messageSource(){
        ReloadableResourceBundleMessageSource source = new ReloadableResourceBundleMessageSource();
        source.setBasename("classpath:i18n/messages");
        source.setUseCodeAsDefaultMessage(true);    
        source.setDefaultEncoding( propWebEncoding );
        source.setCacheSeconds(0); /* check the last-modified timestamp */
        return source;
    }

我的文件位于:

src/main/resources/i18n/messages_es.properties
src/main/resources/i18n/messages_en.properties

我的语言环境是“en” 当我在 HTML (Thymeleaf) 中使用消息“myproperty.example”时,它工作正常,但当我尝试在我的 @Controller@Service 中使用以下方法获取消息时却不行:

@Autowired MessageSource messageSource;

messageSource.getMessage(“myproperty.example”, null, Locale.EN);

它引发 NoSuchMessageException 无法找到的异常......对于区域设置“en” 这都是用 maven 配置的,我的 i18n 文件位于以下目标文件夹中: WEB-INF/classes/i18n/ [files]

我做错了什么?

问题:我在两个不同的环境中工作。我在@Service 层 (getRootConfigClasses) 中调用 MessageSource,它是在 ServletConfigClasses 中配置的。

解决方案:仅在根上下文中工作 (getRootConfigClasses)