[英]I have custom annotation @DTO that transform body from dto to entity however swagger takes the entity to create parameters not DTOs
這是我的控制器請求
@PostMapping("/requestApproval")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<MessageResponse> requestApproval(@DTO(TripIdDTO.class) Trip requestingApprovalTrip) {
this.tripService.requestApproval(requestingApprovalTrip);
return ResponseEntity.ok().body(new MessageResponse("Trip status has been changed to WAITING_FOR_APPROVAL!"));
}
注釋從 JSON 格式獲取請求正文,將其轉換為 DTO,然后轉換為Trip
實體類型。
Swagger 使用 Trip 實體的字段生成參數。 有沒有辦法自定義 swagger 以使用TripIdDTO
類為Trip
的文檔創建參數?
由於該項目不遵守 Swagger 和 Spring Boot 之間通常的約定,因此應該進行一些額外的設置以使其按預期工作。
@Configuration
// Only need for swagger 2.9.2
@EnableSwagger2
public class SpringFoxConfig {
@Bean
public Docket api() {
TypeResolver resolver = new TypeResolver();
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build().additionalModels(resolver.resolve(MessageDto.class));
}
}
@RestController
public class TestController {
@RequestMapping(value = "/message",
produces = {"application/json;charset=utf-8"},
consumes = {"application/json;charset=utf-8"},
method = RequestMethod.POST)
@ApiImplicitParams({
@ApiImplicitParam(name = "request", required = true,
dataType = "MessageDto", paramType = "body")
})
ResponseEntity<?> createMessage(Message message) {
return null;
}
}
通過這樣做,我們聲明了一個類型為MessageDto
的參數,應該從 HTTP 請求正文中獲取。
@Data
public class Message {
@ApiModelProperty(hidden = true)
private Integer code = null;
@ApiModelProperty(hidden = true)
private String message = null;
}
Message
類有兩個公共get
方法(我認為這也是你的情況)。 由於除了Message
沒有@RequestBody
,Swagger 會將Message
所有字段視為查詢參數。 為了使這些無用的部分在 API 文檔中不可見,我們應該將它們標記為隱藏。
此功能在 Swagger 2.9.2 中正常工作,在 3.0.0 中不起作用。 這是一個錯誤,我想這需要一些時間來修復。 您可以在springfox 問題 #3435 中找到更多信息。
所有代碼都可以在這個 repo-swagger 演示中找到。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.