簡體   English   中英

我有自定義注釋@DTO 將主體從 dto 轉換為實體,但是 swagger 將實體用於創建參數而不是 DTO

[英]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 之間通常的約定,因此應該進行一些額外的設置以使其按預期工作。

Step 1 注冊真實的API模型

@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));
  }
}

步驟 2 告訴 Swagger 使用的真實 API 模型

@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 請求正文中獲取。

步驟 3 告訴 Swagger 忽略現有參數

@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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM