SpringBoot——2.7.3版本整合Swagger3
发布人:shili8
发布时间:2024-04-26 05:46
阅读次数:40
在现代的Web开发中,API文档的编写和管理是非常重要的一环。Swagger是一个流行的API文档工具,它可以帮助开发者快速地生成API文档,并提供交互式的API测试功能。在SpringBoot项目中整合Swagger可以让我们更方便地管理和查看API文档,提高开发效率。
本文将介绍如何在SpringBoot2.7.3版本中整合Swagger3,并展示如何使用Swagger来生成API文档。
###1. 添加Swagger依赖首先,我们需要在`pom.xml`文件中添加Swagger的依赖:
xml<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
###2. 配置Swagger接下来,我们需要在SpringBoot的配置类中配置Swagger。我们可以创建一个`SwaggerConfig`类来配置Swagger:
javaimport org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; @Configurationpublic class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.OAS_30) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build(); } }
在上面的配置中,我们指定了扫描的包路径为`com.example.controller`,这样Swagger就会扫描该包下的Controller类,并生成API文档。
###3. 编写Controller类接下来,我们编写一个简单的Controller类来演示Swagger的使用:
javaimport org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestControllerpublic class HelloController { @GetMapping("/hello") public String hello() { return "Hello, Swagger!"; } }
###4. 启动应用程序现在,我们可以启动SpringBoot应用程序,并访问` UI界面中,我们可以看到我们编写的`HelloController`类的API接口信息,并可以进行测试。
###5. 高级配置除了基本的配置外,Swagger还提供了许多高级配置选项,例如自定义API文档的标题、描述、版本号等。我们可以在`SwaggerConfig`类中进行配置:
javaimport org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; @Configurationpublic class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.OAS_30) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Swagger API Documentation") .description("This is a sample API documentation using Swagger") .version("1.0") .build(); } }
在上面的配置中,我们通过`ApiInfoBuilder`类来自定义API文档的标题、描述和版本号。这样我们就可以在Swagger UI界面中看到我们自定义的API文档信息。
### 总结通过本文的介绍,我们学习了如何在SpringBoot2.7.3版本中整合Swagger3,并展示了如何使用Swagger来生成API文档。Swagger是一个非常强大的API文档工具,可以帮助我们更方便地管理和查看API文档,提高开发效率。希望本文对你有所帮助,谢谢阅读!