【问题标题】:Spring: No message found under code for locale 'en_US'Spring:在语言环境“en_US”的代码下找不到消息
【发布时间】:2011-11-03 20:27:41
【问题描述】:

applicationContext-Service.xml

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basenames">
        <list><value>messages</value></list>
    </property>
</bean>

我在 /src/messages_en_US.properties 下有 messages_en_US.properties

registerForm.passwordNotMatch=Password does not match.

这是导致错误的代码行:

binding.addError(new FieldError(REGISTER_FORM, "passwordNotMatch", messageSource.getMessage("registerForm.passwordNotMatch", null, locale)));

错误:在区域设置“en_US”的代码“registerForm.passwordNotMatch”下找不到消息。

可能出了什么问题?

【问题讨论】:

  • applicationContext-Service.xml 声明在哪里?

标签: java spring


【解决方案1】:

如果你改成这样行吗:

classpath:messages

?

我的经验是如果使用ReloadableResourceBundleMessageSource,在jsp中会找不到属性文件。在basename 之前添加classpath: 解决了我的问题。

虽然我的项目是由 maven 管理的,但我想你还是可以试一试。

【讨论】:

    【解决方案2】:

    对于那些将@Bean 注释用于bundleMessageSource 的人。 为@Bean 添加名称

    name="messageSource"

    使用我们在@RestController 类中创建MessageSource 对象时使用的相同名称

    @RestController
    public class HelloWorldController {
    
        @Autowired
        private MessageSource messageSource;
    
        @GetMapping(path = "/hello-world-internationalized")
        public String helloWorldInternationalized(@RequestHeader(name = "Accept-Language", required = false) Locale locale) {
            return messageSource.getMessage("good.morning.message", null, locale);
        }
    }
    

    然后在@SpringBootApplication类中

    @Bean(name="messageSource")//wont work without the bean name
    public ResourceBundleMessageSource bundleMessageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("messages");
        return messageSource;
    }
    

    推荐this link

    【讨论】:

      【解决方案3】:

      我有同样的问题。我试过classpath:,但没有任何区别。最后在我的属性文件的最后一行输入了一个回车(所以光标位于下一行,即文件的末尾)。

      另外,如果您使用 Maven 并且您将属性文件放置如下:/resources/xxxx.properties,则资源目录会自动拉入您生成的战争中,因此不需要classpath:

      【讨论】:

      • 准确来说,目录应该是PROJECT_BASE/src/main/resources/,只是为了避免混淆
      【解决方案4】:

      我认为应该是&lt;property name="basename"&gt;,而不是&lt;property name="basenames"&gt;

      【讨论】:

      • 没关系。 setBasename() 接受单个 StringsetBasenames() 接受 Strings 的数组。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      • 1970-01-01
      • 2021-01-19
      • 2013-02-10
      • 1970-01-01
      • 2012-06-11
      相关资源
      最近更新 更多