苍穹外卖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 拥有庞大的社区和丰富的文档,易于学习和使用。
相关推荐
风象南几秒前
SpringBoot 控制器的动态注册与卸载
java·spring boot·后端
我是一只代码狗27 分钟前
springboot中使用线程池
java·spring boot·后端
hello早上好40 分钟前
JDK 代理原理
java·spring boot·spring
PanZonghui44 分钟前
Centos项目部署之Java安装与配置
java·linux
沉着的码农1 小时前
【设计模式】基于责任链模式的参数校验
java·spring boot·分布式
Mr_Xuhhh1 小时前
信号与槽的总结
java·开发语言·数据库·c++·qt·系统架构
何苏三月2 小时前
SpringCloud系列 - Sentinel 服务保护(四)
spring·spring cloud·sentinel
纳兰青华2 小时前
bean注入的过程中,Property of ‘java.util.ArrayList‘ type cannot be injected by ‘List‘
java·开发语言·spring·list
coding and coffee2 小时前
狂神说 - Mybatis 学习笔记 --下
java·后端·mybatis
千楼2 小时前
阿里巴巴Java开发手册(1.3.0)
java·代码规范