主题
Swagger2
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。
Swagger2(现在称为 OpenAPI 3.0)是 Swagger 的一个版本,它提供了一种简单直观的方式来设计和文档化 REST API。
1. 添加依赖
在你的 pom.xml
或者 build.gradle
文件中添加 Swagger2 的依赖。
Maven
xml
<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>
</dependency>
Gradle
groovy
implementation 'io.springfox:springfox-swagger2:2.9.2'
implementation 'io.springfox:springfox-swagger-ui:2.9.2'
2. 配置 Swagger
创建一个配置类来设置 Swagger 的具体参数,如 API 的标题、描述、版本等。
java
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Collections;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfo(
"My REST API",
"Some custom description of API.",
"API TOS",
"Terms of service",
new Contact("敏哥", "www.diyai.cn", "wxmgcs@foxmail.com"),
"License of API", "API license URL", Collections.emptyList());
}
}
3. 访问 Swagger UI
启动你的 Spring Boot 应用,然后在浏览器中访问 http://localhost:8080/swagger-ui.html
来查看和测试你的 API。
注意事项
- 确保你的 API 控制器类或方法使用了正确的注解,如
@Api
,@ApiOperation
,@ApiModel
,@ApiModelProperty
等,以便 Swagger 能够正确解析它们。 - 你可能需要根据你的具体需求调整 Swagger 的配置,例如,选择哪些控制器或路径应该包含在文档中。