Есть ли способ показать сообщение об ограничении - PullRequest
0 голосов
/ 22 марта 2020

У меня есть класс 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")
                        )
                ));
    }

Ответы [ 2 ]

1 голос
/ 24 марта 2020

По умолчанию REST Docs ConstraintDescriptions использует ResourceBundleConstraintDescriptionResolver, чтобы получить описание для каждого ограничения. Как следует из названия, он использует ResourceBundle для предоставления описаний. Вы можете предоставить собственную реализацию ConstraintDescriptionResolver для использования другого механизма. В вашем случае вы хотите использовать message из аннотации ограничения, как показано в следующем примере:

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);
});
0 голосов
/ 24 марта 2020

С помощью ответа Энди вот окончательный результат

import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.snippet.Attributes.key;

import java.util.regex.Pattern;

import org.springframework.restdocs.constraints.ConstraintDescriptions;
import org.springframework.restdocs.constraints.ResourceBundleConstraintDescriptionResolver;
import org.springframework.restdocs.payload.FieldDescriptor;
import org.springframework.util.StringUtils;

public class ConstrainedFields
{
    private final ConstraintDescriptions constraintDescriptions;

    public ConstrainedFields(Class<?> input) {

        ResourceBundleConstraintDescriptionResolver fallback = new ResourceBundleConstraintDescriptionResolver();
        this.constraintDescriptions = new ConstraintDescriptions(input, (constraint) -> {
            String message = (String) constraint.getConfiguration().get("message");
            if (message != null && !Pattern.compile("\\{(.*?)\\}").matcher(message).matches()) {
                return message;
            }
            return fallback.resolveDescription(constraint);
        });     
    }

    public FieldDescriptor withPath(String path) 
    {
        return fieldWithPath(path).attributes(key("constraints").value(StringUtils
                .collectionToDelimitedString(constraintDescriptions
                        .descriptionsForProperty(path), ". ")));
    }
}
...