SpringBoot中怎么使用Swagger生成API文档

2024-04-18

在Spring Boot中使用Swagger生成API文档主要分为以下几个步骤:

  1. 添加Swagger依赖:在pom.xml文件中添加Swagger相关的依赖,例如:
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
  1. 配置Swagger:创建一个配置类,配置Swagger的一些基本信息,例如:
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }
}
  1. 运行应用程序:启动Spring Boot应用程序,访问http://localhost:8080/swagger-ui/index.html即可查看生成的API文档。

通过以上步骤,就可以在Spring Boot应用中集成Swagger并生成API文档了。Swagger还提供了很多自定义配置选项,可以根据实际需求进行配置。