spring-restdocs - 有没有办法显示约束消息
问题描述
我有 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")
)
));
}
解决方案
默认情况下,REST DocsConstraintDescriptions
使用 aResourceBundleConstraintDescriptionResolver
来获取每个约束的描述。顾名思义,它使用 aResourceBundle
来提供描述。您可以提供自己的实现ConstraintDescriptionResolver
来使用不同的机制。在您的情况下,您希望使用message
from 约束注释,如下例所示:
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);
});
推荐阅读
- laravel - Laravel 属于到 where 条件
- python-3.x - 如何使用请求知道 API 的响应数据类型
- c# - 如何使集成测试中的请求有效?
- android - 如何设置底片的最大高度可以以其他方式 WRAP_CONTENT?
- angular - Angular 中的变更检测是重新渲染 DOM 的唯一机制吗?
- azure - 使用 Terraform 通过 Microsoft.Storage.BlobCreated 事件创建 Azure 事件订阅过滤
- sql - 按日期透视预订状态
- machine-learning - 我在训练 BERT 模型时出错
- java - 如何在android中模糊imageview的背景图像
- html - 选择不带标签的自由子元素的 XPath