Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 无法从messages.properties文件读取验证消息_Spring_Spring Mvc_Hibernate Validator_Spring Restcontroller_Spring Rest - Fatal编程技术网

Spring 无法从messages.properties文件读取验证消息

Spring 无法从messages.properties文件读取验证消息,spring,spring-mvc,hibernate-validator,spring-restcontroller,spring-rest,Spring,Spring Mvc,Hibernate Validator,Spring Restcontroller,Spring Rest,我正在创建一个简单的SpringREST应用程序,下面是我的Spring配置类 @Configuration @EnableWebMvc @ComponentScan( basePackages = "com.example.spring" ) public class AppConfig { @Bean public ReloadableResourceBundleMessageSource messageSource() { ReloadableRes

我正在创建一个简单的SpringREST应用程序,下面是我的Spring配置类

@Configuration
@EnableWebMvc
@ComponentScan( basePackages = "com.example.spring" )
public class AppConfig {    
    @Bean
    public ReloadableResourceBundleMessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:/messages");
        return messageSource;
    }   
}
这就是我在控制器课上所做的

@RequestMapping(value = "/create", method = RequestMethod.POST)
    public ResponseEntity<Map<String, String>> createEmployee(@Valid @RequestBody EmployeeModel employeeModel, BindingResult result) {
        if (result.hasErrors()) {
            System.out.println("Errors: " + result.getAllErrors());
            Map<String, String> response = new HashMap<>();
            response.put("status", "failure");
            return new ResponseEntity<>(response, HttpStatus.OK);
        }
        employeeService.createEmployee(employeeModel);
        Map<String, String> response = new HashMap<>();
        response.put("status", "success");
        return new ResponseEntity<>(response, HttpStatus.OK);
    }
这是我的messages.properties文件,它位于src/main/resources文件夹中

NotEmpty.employeeModel.name = Employee name is required.
但我无法读取此错误消息,我只收到@NotEmpty的默认消息

我甚至尝试了以下配置

@Bean
public MessageSource messageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBasename("classpath:/messages");
    return messageSource;
}

请帮我做这个

您需要告诉
验证器
使用您的
消息源

@Bean
public javax.validation.Validator validator() {
    final LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
    factory.setValidationMessageSource(messageSource());
    return factory;
}

@Bean
public ReloadableResourceBundleMessageSource messageSource() {
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasename("classpath:/messages");
    return messageSource;
}
并在模型上指定消息键:

@NotEmpty(message = "{NotEmpty.employeeModel.name}")
private String name;
如果还开着的话可能会有帮助。 在类似的情况下,我明确使用插值器解决了这个问题:

 <!-- Messagesource for locales -->
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basenames">
            <util:list>
                <value>classpath:locales/messages/validation</value>
            </util:list>
        </property>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

    <bean id="resourceBundleMessageInterpolator"
          class="org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator">
        <constructor-arg index="0">
            <bean class="org.springframework.validation.beanvalidation.MessageSourceResourceBundleLocator">
                <constructor-arg index="0" ref="messageSource"/>
            </bean>
        </constructor-arg>
    </bean>

    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="messageInterpolator" ref="resourceBundleMessageInterpolator"/>
    </bean>

    <mvc:annotation-driven validator="validator" />
此外,以下线程提示对我来说也是必须的:


嗯,也许有点晚了,但这对我来说确实有效

尝试更改此消息的
消息源
配置:

@Bean
public MessageSource MessageSource(){
ReloadableResourceBundleMessageSource=新的ReloadableResourceBundleMessageSource();
messageSource.setBasenames(“类路径:/messages”);
messageSource.setUseCodeAsDefaultMessage(false);
setCacheSeconds((int)TimeUnit.HOURS.toSeconds(1));
messageSource.setFallbackToSystemLocale(false);
返回消息源;
}
您的
LocalValidatoryFactoryBean
应该与您已经定义的内容相同

@Bean
公共LocalValidatoryFactoryBean验证器(){
最终LocalValidatorFactoryBean LocalValidatorFactoryBean=新的LocalValidatorFactoryBean();
setValidationMessageSource(messageSource());
返回localvalidatoryFactoryBean;
}

我使用
Spring5.0.1.Final
HibernateValidator5.4.2.Final
版本进行了测试。

老问题,但这对我有效:

    @Bean
    public LocalValidatorFactoryBean localValidatorFactoryBean(final MessageSource messageSource) {
        final LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
        localValidatorFactoryBean.setValidationMessageSource(messageSource);
        return localValidatorFactoryBean;
    }

在一切正常后,应用上提到的所有修复 堆栈溢出并花费数小时使其工作,我终于能够通过在messages.properties文件中添加以下内容来修复它

“#禁止检查整个文件的“UnusedProperty”


请注意,我正在使用intellij,但出于某种奇怪的原因,它没有读取我的消息。

您能同时提供MessageSource bean的代码吗。@karthi我已经将您的代码用于MessageSource bean定义。@karthi嗯,尝试使用
factory.setValidationMessageSource(MessageSource())而不是作为方法参数的注入。我已经修改了答案来反映这一点。我们是否需要像这里讨论的那样在其他任何地方使用验证器bean?现在它给我消息键作为错误消息。它仍然不起作用。你有没有得到答案?我有完全相同的问题,下面的任何建议都无法解决。这不起作用。如果您以某种方式运行了它,您可以在github这样的地方共享整个代码吗?这是可行的,您可能希望在这里检查配置。在投反对票之前,也许你应该努力测试和分享你的结果,不要指望别人会为你努力。我做到了。和。我得出的结论是,这只适用于SpringMVC(就像您的示例一样)。这不适用于常规Json有效负载(即RESTAPI)。为了使我能够工作,我必须编写自己的代码,请参阅。如果我从常规JSON有效负载中得到您的观点。。。您可以在使用
@RequestBody
。。。SpringMVC和RESTAPI没有这样的区别。。。顺便说一下,如果你认为你的代码是正确的方法,也许你可以发布你的答案,这样别人就可以从中受益。这帮助了我!我在将spring(和sprig安全性)从3升级到5、将hibernate从5升级到6以及更多的小升级之后遇到了问题中报告的问题。。。。属性文件中的消息开始找不到,也没有显示(在升级之前),谢谢!
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="validationMessageSource" ref="messageSource"/>
</bean>
@NotNull(message = "{message.notnull}")
    @Bean
    public LocalValidatorFactoryBean localValidatorFactoryBean(final MessageSource messageSource) {
        final LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
        localValidatorFactoryBean.setValidationMessageSource(messageSource);
        return localValidatorFactoryBean;
    }