使用Swagger生成API文档

2021-04-20 10:13:52
Swagger 3.0 实现了零配置,只需要加上这个依赖就行了: > Swagger 3.0 不支持 spring-boot 2.6.x 及以上版本 ``` <!-- https://mvnrepository.com/artifact/io.springfox/springfox-boot-starter --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> ``` 启动项目后,访问 ``` http://localhost:8080/swagger-ui/ ``` 个性化配置 ``` import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.*; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; @Configuration public class SwaggerConfig { @Value("${spring.profiles.active:NA}") private String active; @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) //OAS_30 .enable("dev".equals(active))// 仅在开发环境开启Swagger .apiInfo(apiInfo()) .host("http://www.example.com") // Base URL .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) // .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class)) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API文档") .description("这是描述信息") .contact(new Contact("张三", null, null)) .version("1.0") .build(); } } ``` SwaggerConfig 中配置的包名为 `com.example.controller`,请根据项目实际包名进行修改。 application.properties 中修改 `spring.profiles.active=dev`,这样就只会在开发环境显示api文档。 ``` @Api(tags = "公司相关接口") @RestController public class CompanyController { @ApiOperation("公司列表") @GetMapping(path = "/list") JsonResult<CompanyList> listCompanies() { } } ``` ``` public class Foo { @ApiModelProperty(value = "姓名", required = true) @NotBlank(message = "作者名称[name]") private String name; @ApiModelProperty(value = "排序") private int sort; @ApiModelProperty(value = "单价", example = "12.34", required = true) @NotBlank(message = "单价不能为空[price]") @DecimalMin(value = "0.01", message = "单价不能为0[price]") private String price; @ApiModelProperty(value = "创建时间", example = "2020-01-30 13:24:35") private Date createdAt; @JsonIgnore //json忽略此字段 @ApiModelProperty(hidden = true) //swagger忽略此字段 public boolean isSuccess() { return code.equals("SUCCESS"); } @JsonProperty("close_time") // json使用下划线 private String closeTime; } ``` 一些常用注解说明 ``` @Api:用在controller类,描述API接口 @ApiOperation:描述接口方法 @ApiModel:描述对象 @ApiModelProperty:描述对象属性 @ApiImplicitParams:描述接口参数 @ApiResponses:描述接口响应 @ApiIgnore:忽略接口方法 ``` 如果做安全拦截相关url如下 ``` /swagger-ui/** /swagger-resources/** /v2/api-docs/** /v3/api-docs/** ```