苍穹外卖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 拥有庞大的社区和丰富的文档,易于学习和使用。
相关推荐
qq_2546744125 分钟前
Cisco Nexus 9504交换机上
java·linux·服务器
咕噜企业分发小米28 分钟前
腾讯云在多云管理工具上如何实现合规性要求?
java·云计算·腾讯云
invicinble1 小时前
关于对后端开发工程师,在项目层面的基本需求与进阶方向
java
懒鸟一枚1 小时前
Java17新特性详解
java
戌中横1 小时前
JavaScript 对象
java·开发语言·javascript
crossaspeed1 小时前
面向对象的三大特征和反射(八股)
java·开发语言
zfj3211 小时前
java synchronized关键字用法和底层原理
java·开发语言·轻量级锁·重量级锁·偏向锁·线程同步
梵高的代码色盘1 小时前
互联网大厂Java求职面试实录与技术深度解析
java·spring·缓存·微服务·面试·互联网大厂·技术深度
E_ICEBLUE1 小时前
Excel vs CSV:在系统数据处理中该如何选择?
java·excel·csv·格式转换
郑州光合科技余经理2 小时前
同城020系统架构实战:中台化设计与部署
java·大数据·开发语言·后端·系统架构·uni-app·php