Spring Boot提供了集成Swagger
来自动生成API文档的功能,让开发者更方便地查看和测试API。
详细步骤如下:
1. 添加Swagger的依赖
首先,在Spring Boot项目的 pom.xml 文件中添加Swagger的依赖:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
2. Swagger配置类
创建一个Swagger配置类来配置Swagger文档:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("your.base.package"))
.build();
}
}
3. application.properties
在 application.properties 或 application.yml 文件中配置Swagger相关信息(可选):
springfox.documentation.swagger.v2.path=/api-docs
- 启动应用程序后,访问 http://localhost:8080/swagger-ui/即可查看生成的API文档并进行测试。