苍穹外卖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 拥有庞大的社区和丰富的文档,易于学习和使用。
相关推荐
HoneyMoose5 小时前
Jenkins Cloudflare 部署提示错误
java·servlet·jenkins
阿丰资源5 小时前
基于SpringBoot的物流信息管理系统设计与实现(附资料)
java·spring boot·后端
Predestination王瀞潞5 小时前
Java EE3-我独自整合(第四章:Spring bean标签的常见配置)
java·spring·java-ee
overmind5 小时前
oeasy Python 121[专业选修]列表_多维列表运算_列表相加_列表相乘
java·windows·python
资深数据库专家5 小时前
总账EBS 应用服务器1 的监控分析
java·网络·数据库
房开民5 小时前
可变参数模板
java·开发语言·算法
t***5446 小时前
如何在现代C++中更有效地应用这些模式
java·开发语言·c++
_深海凉_6 小时前
LeetCode热题100-最小栈
java·数据结构·leetcode
不知名的忻6 小时前
Morris遍历(力扣第99题)
java·算法·leetcode·morris遍历
daidaidaiyu6 小时前
一文学习入门 ThingsBoard 开源物联网平台
java·mqtt·spring