苍穹外卖Day01-2

目录

导入接口文档

创建项目​编辑

[导入接口文件 ​编辑](#导入接口文件 编辑)

导入结果界面​编辑

Swagger

介绍

[如何集成 Swagger?](#如何集成 Swagger?)

1.添加依赖

[2.配置 Swagger](#2.配置 Swagger)

[3.创建 Swagger 配置类](#3.创建 Swagger 配置类)

4.使用注解生成文档

[5.访问 Swagger UI](#5.访问 Swagger UI)

[6.Swagger 的优势](#6.Swagger 的优势)


导入接口文档

yApi接口管理平台http://api.doc.jiyou-tech.com/

创建项目

导入接口文件

导入结果界面

Swagger

介绍

使用Swagger你只需要按照它的规范去定义接口及接口相关的信息,就可以做到生成接口文档,以及在线接口调试页面 。 官网:https://swagger.io/

Knife4j是为Java MVC框架集成Swagger生成Api文档的增强解决方案。

如何集成 Swagger?

以 Spring Boot 项目为例,可以通过以下步骤集成 Swagger:

1.添加依赖

pom.xml 文件中加入以下依赖:

XML 复制代码
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

2.配置 Swagger

application.properties 文件中添加以下配置:

XML 复制代码
spring.mvc.pathmatch.matching-strategy = ANT_PATH_MATCHER

3.创建 Swagger 配置类

java 复制代码
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.basePackage("com.example.controller"))
                .paths(PathSelectors.any())
                .build();
    }
}

4.使用注解生成文档

Swagger 通过注解自动生成 API 文档。常见的注解有:

  • @Api:用于类上,描述该类的作用。
  • @ApiOperation:用于方法上,描述具体接口的功能。
  • @ApiParam:用于方法参数上,描述参数信息。
  • @ApiResponse:描述接口的响应信息。
java 复制代码
@RestController
@Api(tags = "用户管理")
public class UserController {

    @ApiOperation(value = "获取用户信息", notes = "根据用户ID获取用户信息")
    @GetMapping("/user/{id}")
    public User getUserById(@ApiParam(value = "用户ID", required = true) @PathVariable Long id) {
        // 获取用户逻辑
    }
}

5.访问 Swagger UI

项目启动后,可以通过浏览器访问 http://localhost:8080/swagger-ui/ 查看生成的 API 文档。

6.Swagger 的优势

  • 自动化:通过注解或配置文件,Swagger 可以根据代码自动生成文档,减少人工维护文档的负担。
  • 易于测试:Swagger UI 提供了接口测试的功能,使得前后端开发人员能够快速测试接口的正确性。
  • 广泛的社区支持:作为流行的 API 文档工具,Swagger 拥有庞大的社区和丰富的文档,易于学习和使用。
相关推荐
AD钙奶-lalala2 小时前
Mac OS上搭建 http server
java
皮皮林5515 小时前
SpringBoot 全局/局部双模式 Gzip 压缩实战:14MB GeoJSON 秒变 3MB
java·spring boot
weixin_456904276 小时前
Spring Boot 用户管理系统
java·spring boot·后端
趁你还年轻_6 小时前
异步编程CompletionService
java
DKPT6 小时前
Java内存区域与内存溢出
java·开发语言·jvm·笔记·学习
sibylyue6 小时前
Guava中常用的工具类
java·guava
奔跑吧邓邓子6 小时前
【Java实战㉞】从0到1:Spring Boot Web开发与接口设计实战
java·spring boot·实战·web开发·接口设计
专注API从业者6 小时前
Python/Java 代码示例:手把手教程调用 1688 API 获取商品详情实时数据
java·linux·数据库·python
奔跑吧邓邓子6 小时前
【Java实战㉝】Spring Boot实战:从入门到自动配置的进阶之路
java·spring boot·实战·自动配置
ONLYOFFICE6 小时前
【技术教程】如何将ONLYOFFICE文档集成到使用Spring Boot框架编写的Java Web应用程序中
java·spring boot·编辑器