2016-10-04 43 views
2

自定义消息我添加了一个验证(@javax.validation.Valid)我@RestController并在@RequestBody类我用@NotEmpty注释:为SpringBoot REST风格的Bean验证工作不

public class Invoice { 

    @NotEmpty 
    private String commentText; 

    // omitted 
} 

当缺少commentText REST调用,调用适当的错误返回到客户端:

{ 
    "timestamp": 1475599494823, 
    "status": 400, 
    "error": "Bad Request", 
    "exception": "org.springframework.web.bind.MethodArgumentNotValidException", 
    "errors": [ { 
     "codes":  [ 
     "NotEmpty.invoice.commentText", 
     "NotEmpty.commentText", 
     "NotEmpty.java.lang.String", 
     "NotEmpty" 
     ], 
     "arguments": [  { 
     "codes":   [ 
      "invoice.commentText", 
      "commentText" 
     ], 
     "defaultMessage": "commentText", 
     "code": "commentText" 
     }], 
     "defaultMessage": "may not be empty", 
     "objectName": "invoice", 
     "field": "commentText", 
     "bindingFailure": false, 
     "code": "NotEmpty" 
    }], 
    "message": "Validation failed for object='invoice'. Error count: 1", 
    "path": "/api/invoices/1" 
} 

然后我创建的src /主/资源/ messages.properties与以下内容:

NotEmpty.invoice.commentText=Please type a comment 

的问题是,代替自定义“请键入注释”原始的错误消息被返回给客户端。

我使用SpringBoot 1.4和YAML配置并在Eclipse中运行应用程序。

任何想法的问题可能是?

+0

在这个问题上的任何更新? – user2049132

回答

0

而不是@NotEmpty注释尝试使用替代javax.validation包:@NotNull@Size(min=1)。 同样你会发现你这个示例项目有用:https://github.com/MichaelKnight/ValidandoFormularios

如果由于某种原因,你需要使用@NotEmpty注解,那么你应该创建一个文件ValidationMessages.properties并将其放置到类路径中。

为避免密钥翻译出现问题,您可以指示如下消息密钥:@NotEmpty(message="{NotEmpty.invoice.commentText}")。或者看看这里: http://docs.jboss.org/hibernate/validator/4.3/reference/en-US/html/validator-usingvalidator.html#section-message-interpolation

+0

我用'NotNull.unidentifiedInvoice.commentText =在'messages.properties'中输入了一个注释',但它仍然返回默认的''defaultMessage“:”可能不为空“''试过'@ javax.validation.constraints.NotNull'' –

+0

您是否将类名更改为UnidentifiedInvoice?如果不尝试使用此键:'NotNull.invoice.commentText'。 – eparvan

+0

对不起,是的,我做了......但这不是问题的根源。 –