如何自定义Java Spring @NotNull验证错误消息

4
    @POST
    @Path("")
    @Consumes({"application/x-www-form-urlencoded"})
    TokenDTO login(@ApiParam(value = "The id of the channel used", required = true )  @HeaderParam("channel")  @NotEmpty(message = "email.notempty") String channel) throws Exception;

大家好,我正在尝试验证频道参数是否为空。如果我解析为空,它会直接抛出错误:

{
"code": 26,
"message": "Validation Error: :NotEmpty",
"data": [
    {
        "type": "NotEmpty",
        "property": "",
        "value": null,
        "inputType": "body",
        "attributes": null
    }
],
"source": "XXXX",
"type": "ValidationException",
"guid": "965ee91a-99a1-4ae5-b721-6415a80dad23"
}

请问您如何定制验证错误信息?

编辑:我看过很多文章,介绍了如何自定义“字段”验证消息的方法。但我想要验证一个方法参数。


也许你想添加一个自定义验证注释而不是修改现有的注释: https://stackoverflow.com/questions/46069805/spring-boot-http-get-custom-validation - Blazerg
1个回答

1
在您的参数中,请确保添加花括号,就像这样。
@NotEmpty(message = "{email.notempty}") String email

然后,在你的应用程序配置中定义LocalValidatorFactoryBean:

   @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:ValidationMessages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

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

最后,在类路径中创建一个ValidationMessages.properties文件,其中包含:
email.notempty=E-mail address is required

我创建了一个ValidationMessages.properties文件并添加了属性,但仍然收到相同的错误。 - ps138

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接