Swagger的介绍


一、Swagger是什么?

  Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。

二、Swagger 的优势?

    • 支持 API 自动生成同步的在线文档:使用 Swagger 后可以直接通过代码生成文档,不再需要自己手动编写接口文档了,对程序员来说非常方便,可以节约写文档的时间去学习新技术。
    • 提供 Web 页面在线测试 API:光有文档还不够,Swagger 生成的文档还支持在线测试。参数和格式都定好了,直接在界面上输入参数对应的值即可在线测试接口。

  官网:https://swagger.io/

三、Spring Boot 集成Swagger

  1)、创建一个Spring Boot项目,模板建议选择2.5.6,最新版对2.9.2不兼容。

     2)、在pom.xml里面添加Maven依赖

  

<dependency>
   <groupId>io.springfoxgroupId>
   <artifactId>springfox-swagger2artifactId>
   <version>2.9.2version>
dependency>

<dependency>
   <groupId>io.springfoxgroupId>
   <artifactId>springfox-swagger-uiartifactId>
   <version>2.9.2version>
dependency>
添加Maven依赖

  如图所示:

  (一)

   (二)

  3)添加一个控制器,用于测试

  
package com.example.swaggerdemo2.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        return "Hello Swagger!";
    }
}
控制器代码

  4)添加配置类,启用Swagger

  
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
}
配置类

  5)、浏览器访问http://localhost:8080/swagger-ui.html

   出现这个界面即成功了!!

   注意:如果在pom.xml文件里面添加依赖报错了,或者在SwaggerConfig类中引入@EnableSwagger2报错,解决方法如下:

  (一)点击Maven按钮

   (二)点击刷新按钮

   (三)点击右下角的加载条,查看加载进度,加载完毕即可完成对Maven依赖的添加

   (四)重启服务