首页 > 解决方案 > 有没有办法显示约束消息

问题描述

我有 CategoryDTO 类,我想在其余文档中显示消息“描述不能为空”,而不是“不能为空”。虽然我知道我可以更改此消息,但我可以创建一个约束属性文件并添加以下行它

javax.validation.constraints.NotNull.description=Must not be blank or null 

但我想在 NotNull 注释中显示消息

public class CategoryDTO 
{
    private String id;

    @NotNull(message = "Description can't be null")
    @Size(min = 2 , max=30 , message = "Size must be greater than 2 and less than 30")
    private String description;
}

编辑:

   @Test
    void testFindAll() 
    {

        CategoryDTO fruits = new CategoryDTO();
        fruits.setDescription("Fruits");
        fruits.setId(UUID.randomUUID().toString());


        CategoryDTO Nuts = new CategoryDTO();
        Nuts.setDescription("Nuts");
        Nuts.setId(UUID.randomUUID().toString());

        ConstrainedFields fields = new ConstrainedFields(CategoryDTO.class);

        BDDMockito.when(categoryService.findAll()).thenReturn(Flux.just(fruits,Nuts));

        webTestClient.get().uri(CategoryController.rootURL + "/categories")
        .exchange().expectBodyList(CategoryDTO.class).
        hasSize(2).consumeWith(WebTestClientRestDocumentationWrapper.document("v1/get-all-categories",              
                responseFields(
                        fields.withPath("[]").description("An array of categories"),
                        fields.withPath("[].id").description("Id of category"),
                        fields.withPath("[].description").description("Description of category")
                        )
                ));
    }

标签: spring-restdocs

解决方案


默认情况下,REST DocsConstraintDescriptions使用 aResourceBundleConstraintDescriptionResolver来获取每个约束的描述。顾名思义,它使用 aResourceBundle来提供描述。您可以提供自己的实现ConstraintDescriptionResolver来使用不同的机制。在您的情况下,您希望使用messagefrom 约束注释,如下例所示:

ConstraintDescriptions descriptions = new ConstraintDescriptions(CategoryDTO.class, (constraint) -> {
    return (String) constraint.getConfiguration().get("message");
});
List<String> descriptionProperty = descriptions.descriptionsForProperty("description");
System.out.println(descriptionProperty);

执行时,上面将输出以下内容:

[Description can't be null, Size must be greater than 2 and less than 30]

如果您不总是配置该message属性,您可能希望回退到资源包解析器,如以下示例所示:

ResourceBundleConstraintDescriptionResolver fallback = new ResourceBundleConstraintDescriptionResolver();
ConstraintDescriptions descriptions = new ConstraintDescriptions(CategoryDTO.class, (constraint) -> {
    String message = (String) constraint.getConfiguration().get("message");
    if (message != null) {
        return message;
    }
    return fallback.resolveDescription(constraint);
});

推荐阅读