Swagger教程详解

一、Swagger是什么?

Swagger是一个面向RESTful API的开源软件框架。它提供了一组工具,可以帮助您描述、生成、消费API。通过使用Swagger,您可以更好地了解API的工作方式以及如何使用它。

Spring Boot集成Swagger,可以让我们在开发API文档时,少写很多样板代码,Swagger生成器会根据注解自动生成API文档,并且生成的API文档非常详细,展示了API的参数、请求方式、响应格式等等。

二、快速上手Swagger

1、首先,在pom.xml中引入Swagger的依赖。

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

2、创建Swagger2配置类,配置Swagger基本信息

package com.example.swaggerdemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
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 createApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.swaggerdemo.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SwaggerDemo API")
                .description("SwaggerDemo后台API接口文档")
                .termsOfServiceUrl("http://127.0.0.1:8080/")
                .version("1.0")
                .build();
    }
}

3、在Controller层的方法上使用Swagger注解,用于API的说明、请求参数的说明等。

@Api(tags = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @ApiOperation(value = "获取用户列表")
    @GetMapping("/")
    public List<User> getUserList() {
        return userRepository.findAll();
    }

    @ApiOperation(value = "新增用户")
    @PostMapping("/")
    public User addUser(@ApiParam(value = "用户对象", required = true) @RequestBody User user) {
        return userRepository.save(user);
    }

    @ApiOperation(value = "根据ID查询用户")
    @GetMapping("/{id}")
    public User getUserById(@ApiParam(value = "用户ID", required = true) @PathVariable Long id) {
        return userRepository.findById(id).orElse(null);
    }

    @ApiOperation(value = "根据ID更新用户信息")
    @PutMapping("/{id}")
    public User updateUserById(@ApiParam(value = "用户ID", required = true) @PathVariable Long id,
                               @ApiParam(value = "用户对象", required = true) @RequestBody User user) {
        user.setId(id);
        return userRepository.save(user);
    }

    @ApiOperation(value = "根据ID删除用户")
    @DeleteMapping("/{id}")
    public void deleteUserById(@ApiParam(value = "用户ID", required = true) @PathVariable Long id) {
        userRepository.deleteById(id);
    }
}

三、Swagger的常用注解

Swagger常用注解有@Api、@ApiOperation、@ApiParam、@ApiModel、@ApiModelProperty这些注解。

1、@Api:标记一个Controller类为Swagger资源。

2、@ApiOperation:标记Controller方法为Swagger操作。

3、@ApiParam:标记方法参数的名称和描述。

4、@ApiModel和@ApiModelProperty:用于Swagger Model类的Javadoc。其中,@ApiModel描述模型的名称和说明,@ApiModelProperty描述模型属性的名称、描述信息、是否必须等。

四、Swagger的高级用法

1、全局配置

通过SwaggerConfig的apiInfo()方法,可以设置所有Controller的通用信息。

private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
            .title("SwaggerDemo API")
            .description("SwaggerDemo后台API接口文档")
            .termsOfServiceUrl("http://127.0.0.1:8080/")
            .version("1.0")
            .contact(new Contact("SwaggerDemo", "", "xxx@qq.com")) //设置API创建人信息
            .license("Apache License 2.0")
            .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
            .build();
}

2、局部配置

可以在方法级别上对Swagger进行局部配置,例如针对某个方法不展示。

@ApiOperation(value = "获取用户列表")
@ApiResponses(value = {
    @ApiResponse(code = 401, message = "未授权"),
    @ApiResponse(code = 403, message = "禁止访问")
})
@GetMapping("/")
public List<User> getUserList() {
    return userRepository.findAll();
}

3、返回新的数据类型

在Swagger中,我们可以在ResponseBoby注解中使用ResponseContainer注解定义响应数据的格式,常见的格式有List、Set、Map、具体类等。

@ApiOperation(value = "获取用户列表")
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "获取成功", response = User.class, responseContainer = "List")
})
@GetMapping("/")
public List<User> getUserList() {
    return userRepository.findAll();
}

五、Swagger-UI的使用

Swagger-UI是Swagger的前端框架,可以通过Swagger生成的json或yaml文件来展示API文档。

1、引入Swagger-UI的依赖。

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>swagger-ui</artifactId>
    <version>2.1.4</version>
</dependency>

2、在Spring Boot的配置文件中配置Swagger-UI的访问路径。

spring.mvc.static-path-pattern=/swagger/**
spring.resources.static-locations=classpath:/META-INF/resources/webjars/

3、启用Swagger-UI

在SwaggerConfig类中添加以下代码:

@Bean
public Docket createApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.swaggerdemo.controller"))
            .paths(PathSelectors.any())
            .build();
}

@Bean
public UiConfiguration getUiConfig() {
    return UiConfigurationBuilder.builder()
            .docExpansion(SwaggerUiConfiguration.DocExpansion.LIST)
            .build();
}

4、访问Swagger-UI

启动Spring应用,访问http://localhost:8080/swagger-ui.html,即可看到Swagger-UI的展示界面。

六、总结

本文详细阐述了Swagger的概念、快速上手、常用注解、高级用法以及Swagger-UI的使用,是学习Swagger的不错教程。

原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/309594.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
小蓝小蓝
上一篇 2025-01-04 19:31
下一篇 2025-01-04 19:31

相关推荐

  • MQTT使用教程

    MQTT是一种轻量级的消息传输协议,适用于物联网领域中的设备与云端、设备与设备之间的数据传输。本文将介绍使用MQTT实现设备与云端数据传输的方法和注意事项。 一、准备工作 在使用M…

    编程 2025-04-29
  • Python3.6.5下载安装教程

    Python是一种面向对象、解释型计算机程序语言。它是一门动态语言,因为它不会对程序员提前声明变量类型,而是在变量第一次赋值时自动识别该变量的类型。 Python3.6.5是Pyt…

    编程 2025-04-29
  • Deepin系统分区设置教程

    本教程将会详细介绍Deepin系统如何进行分区设置,分享多种方式让您了解如何规划您的硬盘。 一、分区的基本知识 在进行Deepin系统分区设置之前,我们需要了解一些基本分区概念。 …

    编程 2025-04-29
  • 写代码新手教程

    本文将从语言选择、学习方法、编码规范以及常见问题解答等多个方面,为编程新手提供实用、简明的教程。 一、语言选择 作为编程新手,选择一门编程语言是很关键的一步。以下是几个有代表性的编…

    编程 2025-04-29
  • Qt雷达探测教程

    本文主要介绍如何使用Qt开发雷达探测程序,并展示一个简单的雷达探测示例。 一、环境准备 在开始本教程之前,需要确保你的开发环境已经安装Qt和Qt Creator。如果没有安装,可以…

    编程 2025-04-29
  • 猿编程python免费全套教程400集

    想要学习Python编程吗?猿编程python免费全套教程400集是一个不错的选择!下面我们来详细了解一下这个教程。 一、课程内容 猿编程python免费全套教程400集包含了从P…

    编程 2025-04-29
  • Python烟花教程

    Python烟花代码在近年来越来越受到人们的欢迎,因为它可以让我们在终端里玩烟花,不仅具有视觉美感,还可以通过代码实现动画和音效。本教程将详细介绍Python烟花代码的实现原理和模…

    编程 2025-04-29
  • 使用Snare服务收集日志:完整教程

    本教程将介绍如何使用Snare服务收集Windows服务器上的日志,并将其发送到远程服务器进行集中管理。 一、安装和配置Snare 1、下载Snare安装程序并安装。 https:…

    编程 2025-04-29
  • Python画K线教程

    本教程将从以下几个方面详细介绍Python画K线的方法及技巧,包括数据处理、图表绘制、基本设置等等。 一、数据处理 1、获取数据 在Python中可以使用Pandas库获取K线数据…

    编程 2025-04-28
  • Python语言程序设计教程PDF赵璐百度网盘介绍

    Python语言程序设计教程PDF赵璐百度网盘是一本介绍Python语言编程的入门教材,本文将从以下几个方面对其进行详细阐述。 一、Python语言的特点 Python语言属于解释…

    编程 2025-04-28

发表回复

登录后才能评论