温馨提示×

Ubuntu Swagger集成有哪些步骤

小樊
60
2025-03-26 08:39:54
栏目: 智能运维

在Ubuntu上集成Swagger主要分为以下几个步骤:

1. 添加依赖

首先,你需要在项目的pom.xml文件中添加springfox-swagger2springfox-swagger-ui这两个依赖。例如:

<dependencies> <!-- Swagger 2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>YOUR_DESIRED_VERSION</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>YOUR_DESIRED_VERSION</version> </dependency> <!-- 其他依赖 --> </dependencies> 

YOUR_DESIRED_VERSION替换为实际使用的版本号。

2. 配置Swagger

接下来,创建一个配置类来启用Swagger并定义一些基本信息。例如,对于Spring Boot项目,你可以使用以下代码:

import 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; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } } 

这个配置类启用了Swagger,并告诉Swagger扫描所有的API接口来生成文档。

3. 访问Swagger UI

启动Spring Boot项目后,访问http://localhost:8080/swagger-ui.html(假设服务端口为8080),你应该能够看到Swagger UI界面,其中列出了你的所有API端点。

4. 使用注解描述API

使用Swagger提供的注解来描述API的详细信息。例如:

import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @Api(tags = "Sample API") public class SampleController { @ApiOperation(value = "Get sample data") public CommonResponse getSampleData() { // Your implementation here } } 

5. (可选)使用springdoc-openapi集成Swagger UI

对于Spring Boot 3.x项目,你还可以使用springdoc-openapi来集成Swagger UI,它提供了更简洁的配置方式。首先,添加springdoc-openapi-starter-webmvc-ui依赖到你的pom.xml

<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.8.5</version> </dependency> 

然后,在application.yml中进行简单配置:

springdoc: api-docs: path: /v3/api-docs swagger-ui: path: /dev-tools/ 

这样,你就可以通过访问http://localhost:8080/dev-tools/swagger-ui.html来查看Swagger UI。

以上步骤应该能够帮助你在Ubuntu上成功集成Swagger。如果在集成过程中遇到问题,可以参考相关的官方文档或社区论坛寻求帮助。

0