Spring Boot 学习研究笔记(六) -使用 Swagger 集成文档

简介: Spring Boot 学习研究笔记(六) -使用 Swagger 集成文档

一、为什么要使用Swagger生成文档?

使用 Swagger 集成文档具有以下几个优势:

  • 功能丰富 :支持多种注解,自动生成接口文档界面,支持在界面测试API接口功能;
  • 及时更新 :开发过程中花一点写注释的时间,就可以及时的更新API文档,省心省力;
  • 整合简单 :通过添加pom依赖和简单配置,内嵌于应用中就可同时发布API接口文档界面,不需要部署独立服务。

二、Swagger生成文档步骤:

 

1、生成项目模板

为方便我们初始化项目,Spring Boot给我们提供一个项目模板生成网站。

(1)、打开浏览器,访问:https://start.spring.io/

(2)、根据页面提示,选择构建工具,开发语言,项目信息等。

 

2、添加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>

3、添加配置类

package com.example.demo.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;
/**
 * Swagger API文档配置类
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket restfulApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("API 文档标题")
                .description("API 文档描述")
                .version("1.0.0")
                .build();
    }
}


4、API 文档代码

package com.example.demo.controller;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
@Api(value = "类描述")
@RestController
public class HelloController {
    private final Logger logger = LoggerFactory.getLogger(HelloController.class);
    @ApiOperation(value = "初次见面", notes = "世界您好!")
    @GetMapping("/")
    public String home() {
        return "Hello World!";
    }
    @ApiOperation(value = "向你问好", notes = "hello <名字>")
    @GetMapping("/hello")
    public String hello(@ApiParam(value = "打招呼名字", required = true) @RequestParam String name) {
        return "Hello " + name + "!";
    }
    @ApiOperation(value = "查询车辆接口", notes = "此接口描述xxxxxxxxxxxxx<br/>xxxxxxx<br>值得庆幸的是这儿支持html标签<hr/>", response = String.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "vno", value = "车牌", required = false,
                    dataType = "string", paramType = "query", defaultValue = "辽A12345"),
            @ApiImplicitParam(name = "page", value = "page", required = false,
                    dataType = "Integer", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "count", value = "count", required = false,
                    dataType = "Integer", paramType = "query", defaultValue = "10")
    })
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successful — 请求已完成"),
            @ApiResponse(code = 400, message = "请求中有语法问题,或不能满足请求"),
            @ApiResponse(code = 401, message = "未授权客户机访问数据"),
            @ApiResponse(code = 404, message = "服务器找不到给定的资源;文档不存在"),
            @ApiResponse(code = 500, message = "服务器不能完成请求")}
    )
    @GetMapping("/vehicles")
    public ModelMap findVehicles(@RequestParam(value = "vno", required = false) String vno,
                                 @RequestParam(value = "page", required = false) Integer page,
                                 @RequestParam(value = "count", required = false) Integer count)
            throws Exception {
        logger.info("http://localhost:8501/api/v1/vehicles");
        logger.info("## {},{},{}", vno, page, count);
        logger.info("## 请求时间:{}", LocalDate.now());
        ModelMap map = new ModelMap();
        map.addAttribute("vno", vno);
        map.addAttribute("page", page);
        return map;
    }
}


 

三、spring-boot-swagger2 在项目中常用的注解说明:

(1)、@Api: 属性 value 、description 可用在class头上,class描述

示例代码:

@Api(value = "类描述")

 

(2)、@ApiOperation: 属性 value 、notes 可用在方法头上,参数的描述容器

示例代码:

@ApiOperation(value = "向你问好", notes = "hello <名字>")

 

(3)、@ApiParam、@ApiImplicitParam@ApiImplicitParams:注解API 的参数 ,也就是用于swagger提供开发者文档生成的注释内容。

@ApiParam和@ApiImplicitParam的功能是相同的,但是@ApiImplicitParam的适用范围更广。在非JAX-RS的场合(比如使用servlet提供HTTP接口),只能使用@ApiImplicitParam进行参数说明。我认为,这是因为接口并不显式展示入参的名称,所以没有地方去使用@ApiParam,只能在接口的方法声明下方写@ApiImplicitParam 。

属性说明

  • name:名字, 可用在@ApiImplicitParams
  • value :参数中文描述
  • required: true/false , 代表是否必须传参
  • dataType:参数类型
  • paramType:参数请求方式, 这里有几种形式:

path 以地址的形式提交数据,对应@PathVariable{}path传递。  query 直接跟参数完成自动映射赋值,对应@RequestParam?传递。  body 以流的形式提交 仅支持POST ,@RequestBody  header 参数在request headers 里边提交  form 以form表单的形式提交 仅支持POST

  • defaultValue:可用在方法头上,参数的描述容器

@ApiImplicitParams@ApiImplicitParam数组,可用在方法头上,参数的描述容器。

示例代码:

@ApiImplicitParams({
            @ApiImplicitParam(name = "vno", value = "车牌", required = false,
                    dataType = "string", paramType = "query", defaultValue = "辽A12345"),
            @ApiImplicitParam(name = "page", value = "page", required = false,
                    dataType = "Integer", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "count", value = "count", required = false,
                    dataType = "Integer", paramType = "query", defaultValue = "10")
    })

 

4、@ApiResponses 、@ApiResponse:可用在方法头上,用作返回值的描述。

@ApiResponses 一个包装器,允许列出多个 ApiResponse,若需要描述单个 ApiResponse,你仍然必须使用此注解并将@ApiResponse 包装在一个数组中;

属性名称 数据类型 默认值 说明
value ApiResponse[]   ApiResponse 列表

 

@ApiResponse:在 Rest 接口或类上和 @ApiResponses 组合使用,组装返回参数说明。

属性说明

属性名称 数据类型 默认值 说明
code int   响应的HTTP状态码
message String   伴随响应的人类可读的消息
response Class<?> Void.class 用于描述消息有效负载的可选响应类,对应于响应消息对象的 schema 字段
reference String “” 指定对响应类型的引用,指定的应用可以使本地引用,也可以是远程引用,将按原样使用,并将覆盖任何指定的response()类
responseHeaders ResponseHeader[] @ResponseHeader(name = “”, response = Void.class) 可能响应的 header 列表
responseContainer String “” 声明响应的容器,有效值为List,Set,Map,任何其他值都将被忽略

示例代码:

@ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successful — 请求已完成"),
            @ApiResponse(code = 400, message = "请求中有语法问题,或不能满足请求"),
            @ApiResponse(code = 401, message = "未授权客户机访问数据"),
            @ApiResponse(code = 404, message = "服务器找不到给定的资源;文档不存在"),
            @ApiResponse(code = 500, message = "服务器不能完成请求")}
    )

 

 


相关文章
|
3月前
|
数据可视化 Java BI
将 Spring 微服务与 BI 工具集成:最佳实践
本文探讨了 Spring 微服务与商业智能(BI)工具集成的潜力与实践。随着微服务架构和数据分析需求的增长,Spring Boot 和 Spring Cloud 提供了构建可扩展、弹性服务的框架,而 BI 工具则增强了数据可视化与实时分析能力。文章介绍了 Spring 微服务的核心概念、BI 工具在企业中的作用,并深入分析了两者集成带来的优势,如实时数据处理、个性化报告、数据聚合与安全保障。同时,文中还总结了集成过程中的最佳实践,包括事件驱动架构、集中配置管理、数据安全控制、模块化设计与持续优化策略,旨在帮助企业构建高效、智能的数据驱动系统。
205 1
将 Spring 微服务与 BI 工具集成:最佳实践
|
5月前
|
XML 人工智能 Java
Spring Boot集成Aviator实现参数校验
Aviator是一个高性能、轻量级的Java表达式求值引擎,适用于动态表达式计算。其特点包括支持多种运算符、函数调用、正则匹配、自动类型转换及嵌套变量访问,性能优异且依赖小。适用于规则引擎、公式计算和动态脚本控制等场景。本文介绍了如何结合Aviator与AOP实现参数校验,并附有代码示例和仓库链接。
322 0
|
3月前
|
监控 Cloud Native Java
Spring Integration 企业集成模式技术详解与实践指南
本文档全面介绍 Spring Integration 框架的核心概念、架构设计和实际应用。作为 Spring 生态系统中的企业集成解决方案,Spring Integration 基于著名的 Enterprise Integration Patterns(EIP)提供了轻量级的消息驱动架构。本文将深入探讨其消息通道、端点、过滤器、转换器等核心组件,以及如何构建可靠的企业集成解决方案。
281 0
|
5月前
|
Java 关系型数据库 数据库连接
Spring Boot项目集成MyBatis Plus操作PostgreSQL全解析
集成 Spring Boot、PostgreSQL 和 MyBatis Plus 的步骤与 MyBatis 类似,只不过在 MyBatis Plus 中提供了更多的便利功能,如自动生成 SQL、分页查询、Wrapper 查询等。
448 3
|
9月前
|
JSON Java API
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的使用
本文详细介绍了Swagger2的使用方法,包括在Spring Boot项目中的配置与应用。重点讲解了Swagger2中常用的注解,如实体类上的`@ApiModel`和`@ApiModelProperty`,Controller类上的`@Api`、`@ApiOperation`以及参数上的`@ApiParam`等。通过示例代码展示了如何为实体类和接口添加注解,并在页面上生成在线接口文档,实现接口测试。最后总结了Swagger的优势及其在项目开发中的重要性,提供了课程源代码下载链接供学习参考。
660 0
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的使用
|
9月前
|
缓存 Java API
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
本文介绍了在Spring Boot中配置Swagger2的方法。通过创建一个配置类,添加`@Configuration`和`@EnableSwagger2`注解,使用Docket对象定义API文档的详细信息,包括标题、描述、版本和包路径等。配置完成后,访问`localhost:8080/swagger-ui.html`即可查看接口文档。文中还提示了可能因浏览器缓存导致的问题及解决方法。
1031 0
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
|
9月前
|
Java Maven 微服务
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的 maven 依赖
在项目中使用Swagger2工具时,需导入Maven依赖。尽管官方最高版本为2.8.0,但其展示效果不够理想且稳定性欠佳。实际开发中常用2.2.2版本,因其稳定且界面友好。以下是围绕2.2.2版本的Maven依赖配置,包括`springfox-swagger2`和`springfox-swagger-ui`两个模块。
371 0
|
9月前
|
前端开发 Java API
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档—— Swagger 简介
第6课介绍了在Spring Boot中集成Swagger2以展示在线接口文档的方法。随着前后端分离架构的发展,API文档成为连接前端与后端开发的重要纽带。然而,代码更新频繁导致文档难以同步维护,Swagger2解决了这一问题。通过Swagger,在线API文档不仅方便了接口调用方查看和测试,还支持开发者实时测试接口数据。本文使用Swagger 2.2.2版本,讲解如何在Spring Boot项目中导入并配置Swagger2工具,从而高效管理接口文档。
310 0
|
数据可视化 Java API
Spring Boot与Swagger的集成
Spring Boot与Swagger的集成