将 swagger 与 Spring Boot 或 Spring Cloud 集成非常容易。
只需对现有 REST API 进行一些注释,它就会自动为您生成完整的 swagger 规范。 Swagger 绝对是最流行的 REST API 文档框架之一。
pom.xml 依赖项
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
<scope>compile</scope>
</dependency>
在 springboot 应用程序中定义 api 信息
@Bean
public Docket newsApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("springboot")
.apiInfo(apiInfo())
.select()
.paths(regex("/.*"))
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SpringBoot REST API with Swagger")
.description("SpringBoot REST API with Swagger")
.termsOfServiceUrl("http://www-03.ibm.com/software/sla/sladb.nsf/sla/bm?Open")
.contact("sanket**@au1.ibm.com")
.license("Apache License Version 2.0")
.licenseUrl("https://github.com/IBM-Bluemix/news-aggregator/blob/master/LICENSE")
.version("2.0")
.build();
}
注释
@EnableSwagger2
为您的应用程序类
注释您的 REST API
像这样的东西
@RequestMapping(value = "/operate/add/{left}/{right}", method = RequestMethod.GET, produces = "application/json")
@ApiOperation(value = "addNumbers", nickname = "addNumbers")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Success", response = Result.class),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 500, message = "Failure") })
public Result add(@PathVariable("left") int left, @PathVariable("right") int right) {
你完成了。默认情况下包含 Swagger UI,您还可以访问 JSON 格式的 swagger 规范。使用权http://localhost:12001/swagger-ui.html#/
有关更多详细信息,请参阅此代码库:https://github.com/sanketsw/SpringBoot_REST_API https://github.com/sanketsw/SpringBoot_REST_API