2017-01-09 787 views
1

我在Spring MVC项目(Spring Boot 1.4.2)的表单对象中使用了javax.validation.constraints.AssertTrue注解。Spring验证@AssertTrue自定义错误代码/消息

我的班级与此类似:

public class CommandForm { 

    @NotEmpty 
    @Email 
    private String email; 

    // ... 

    @AssertTrue(message="{error.my.custom.message}") 
    public boolean isValid(){ 
     // validate fields 
    } 
} 

方法isValid正确调用和验证过程中正常工作,但我的自定义错误代码没有被正确解析。

我在我的message.properties文件中有error.my.custom.message字段,但是当验证失败时,我将"{error.my.custom.message}"字符串作为错误消息而不是解析的消息。

我的代码有什么问题?这是设置自定义错误代码的正确语法吗?

回答

0

我搜了一下调试后的溶液。

设置自定义消息的最简单方法是简单地在我的message.properties中定义一个AssertTrue.commandForm.valid字段。

不需要在@AssertTrue注释中设置message参数。

0

我认为唯一的问题是,默认情况下,Java Validation API (JSR-303)会从名为ValidationMessages.properties(在/resources下)的文件中读取这些消息。

创建一个带有该名称的文件并将消息移到那里......然后再试一次。它应该工作!

NOTE:虽然您可以更改文件名,但“按惯例”就是这样命名的。

1

移动邮件到ValidationMessages.properties文件 或覆盖您的WebMvcConfigurerAdaptergetValidator()方法,使您的自定义message.properties弹簧得到加载,如下所示:

import org.springframework.context.MessageSource; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.support.ResourceBundleMessageSource; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.validation.Validator; 
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; 
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 

@Configuration 
public class WebController extends WebMvcConfigurerAdapter { 

    @Override 
    public Validator getValidator() { 
     LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); 
     validator.setValidationMessageSource(messageSource()); 
     return validator; 
    } 

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

}