注解中的Spring Boot JSR303消息代码被忽略 [英] Spring Boot JSR303 message code in annotation getting ignored

查看:189
本文介绍了注解中的Spring Boot JSR303消息代码被忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Spring Boot应用程序中,我有一个支持JSR303验证的备用bean.在注释中,我指定了消息代码:

In my Spring Boot app I have a backing bean where I am using JSR303 validation. In the annotation, I have specified the message code:

@NotBlank(message = "{firstname.isnull}")
private String firstname;

然后在我指定的message.properties中:

Then in my message.properties I have specified:

firstname.isnull = Firstname cannot be empty or blank

我的messageSource的JavaConfig是:

My JavaConfig for the messageSource is:

@Bean(name = "messageSource")
public MessageSource messageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBasename("messages");
    messageSource.setDefaultEncoding("UTF-8");
    return messageSource;
}

验证工作正常,但是我没有在JSP页面中看到消息代码,而是看到了实际的字符串.在查看日志文件时,我看到了一系列代码:

The validation works correctly but instead of seeing the actual string, I get the message code in my jsp page. In looking at the log file, I see an array of codes:

Field error in object 'newAccount' on field 'firstname': rejected value []; codes [NotBlank.newAccount.firstname,NotBlank.firstname,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [newAccount.firstname,firstname]; arguments []; default message [firstname]]; default message [{firstname.isnull}]

如果我将message.properties中的消息代码更改为数组中的代码之一,则该字符串将在我的Web表单中正确显示.我什至不必更改批注中的代码.这向我表明注释的message参数中的代码已被忽略.

If I change the my message code in the message.properties to one of the codes in the array, the string displays correctly in my web form. I didn't even have to change the code in the annotation. This indicates to me the code in the message parameter of the annotation is getting ignored.

我不想使用默认代码.我想用我自己的.我该如何进行这项工作.您能提供一个代码示例吗?

I don't want to use the default code. I want to use my own. How can I make this work. Can you please provide a code example.

推荐答案

JSR303插值通常可用于ValidationMessages.properties文件.但是,您可以配置Spring以根据需要进行更改(我很懒():)

JSR303 interpolation normally works with ValidationMessages.properties file. However you can configure Spring to change that if you want (I was lazy to do so :)) e.g.

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

<mvc:annotation-driven validator="validator" />

这篇关于注解中的Spring Boot JSR303消息代码被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆