【发布时间】:2020-06-13 12:24:32
【问题描述】:
我看到在 Spring Boot 应用程序的 swagger ui 中显示了很多不需要的字段。
我的 swagger 依赖项是
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
我的 Rest Controller 代码是这样的
@ApiOperation(value = "Get Data")
@GetMapping(value = "/applicant", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getApplicant(@Valid ApplicantRequestBean
applicantRequestBean, Errors errors) throws APIValidationException {
if (errors.hasErrors()) {
//check for constraintsviolation here and throw an error if found
throw new APIValidationException(HttpStatus.BAD_REQUEST, "Bad Request", errorWrapper);
}
}
我的 ApplicationRequestBean 有
@NotBlank(message = "Id is mandatory")
@Size(min = 9, max = 9, message = "Id should be 9 characters long")
@ApiModelProperty(example = "@12345678", value = "Applicant Id", position = 3)
private String id=null;
@NotBlank(message = "Date of Birth is mandatory")
@ApiModelProperty(example = "30-12-2000", value = "Applicant Date of Birth in DD-MM-YYYY format", position = 2)
private String dateOfBirth=null;
@Email
@ApiModelProperty(example = "id@domain.com", value = "Applicant Email Id", position = 1)
private String emailId=null;
@ApiModelProperty(example = "971505504XXX", value = "Applicant Contact Number", position = 0)
private String contactNumber=null;
我的 APIValidationException 类扩展了 RuntimeException 并具有三个字段
private HttpStatus status;
private String message;
private Object errors;
我的扩展了 ResponseEntityExceptionHandler 的 CustomExceptionHandler 是这样的
@RestControllerAdvice 公共类 CustomExceptionHandler 扩展了 ResponseEntityExceptionHandler {
@ExceptionHandler(APIValidationException.class)
public final ResponseEntity<Object> handleAPIValidationExceptions(APIValidationException ex, WebRequest request) {
ErrorResponse error = new ErrorResponse("error", ex.getMessage(), ex.getErrors());
return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
}
最后MySwaager Config是这样的
public Docket swaggerConfiguration() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName(swaggerGroupName)
.select()
.paths(PathSelectors.ant("/api/**"))
.apis(RequestHandlerSelectors.basePackage("a.b.c.d"))
.build()
.apiInfo(apiInfo())
.tags(new Tag("Applicant", "Applicant APIs"));
}
【问题讨论】:
标签: spring-boot swagger swagger-ui