SpringBoot整合Swagger2实现接口文档

展示一下

访问方式一

访问地址:http://localhost:8080/swagger-ui.html#/

首页

在这里插入图片描述

详情页

在这里插入图片描述

访问方式二

访问地址:http://localhost:8080/doc.html

首页

在这里插入图片描述

侧边栏

在这里插入图片描述

详情页

在这里插入图片描述

在这里插入图片描述

用途介绍

现在的开发模式都是前后端分离,在联调阶段,后端同学需要向前端同学提供api文档。
一个清晰加美观的文档可以减少很多口水仗,是维护和谐开发氛围的必需品。

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。
它有如下几个特点:

1.及时性 (接口变更后,能够及时准确地通知相关前后端开发人员)

2.规范性 (并且保证接口的规范性,如接口的地址,请求方式,参数及响应格式和错误信息)

3.一致性 (接口信息一致,不会出现因开发人员拿到的文档版本不一致,而出现分歧)

4.可测性 (直接在接口文档上进行测试,以方便理解业务)

尝试一下

1、配置文件

SpringBoot项目pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot-swagger</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-swagger</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

这里需要注意一个版本对应的问题,如果使用了高版本的SpringBoot框架,低版本的Swagger,
会出现如下报错:

org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
	at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181)
	at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54)
	at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356)
	at java.lang.Iterable.forEach(Iterable.java:75)
	at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155)
	at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123)
	at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586)
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145)
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:740)
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:415)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312)
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301)

这是因为:因为Springfox 使用的路径匹配是基于AntPathMatcher的,而Spring Boot 2.6.X使用的是PathPatternMatcher。

以下几个版本是兼容的

SpringBoot版本 Swagger版本
2.5.6 2.9.2
SpringBoot版本 Swagger版本
2.6.5 3.0.0

2、项目代码

项目结构

在这里插入图片描述

SwaggerConfig.java

package com.example.springbootswagger.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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
public class SwaggerConfig {

    @Bean
    public Docket createDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(true)
                .groupName("我的接口文档")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.springbootswagger.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //标题
                .title("凤求凰")
                //作者、链接、邮箱等
                .contact(new Contact(
                        "司马相如",
                        "https://hanyu.baidu.com/shici/detail?pid=ecb82707a98c418995c5a0c50b770af0&from=kg0",
                        ""
                ))
                //描述
                .description("有一美人兮,见之不忘。\n" +
                        "一日不见兮,思之如狂。\n" +
                        "凤飞翱翔兮,四海求凰。\n" +
                        "无奈佳人兮,不在东墙。\n" +
                        "将琴代语兮,聊写衷肠。\n" +
                        "何日见许兮,慰我彷徨。\n" +
                        "愿言配德兮,携手相将。\n" +
                        "不得於飞兮,使我沦亡。\n" +
                        "凤兮凤兮归故乡,遨游四海求其凰。\n" +
                        "时未遇兮无所将,何悟今兮升斯堂!\n" +
                        "有艳淑女在闺房,室迩人遐毒我肠。\n" +
                        "何缘交颈为鸳鸯,胡颉颃兮共翱翔!\n" +
                        "凰兮凰兮从我栖,得托孳尾永为妃。\n" +
                        "交情通意心和谐,中夜相从知者谁?\n" +
                        "双翼俱起翻高飞,无感我思使余悲。")
                //更新说明
                .termsOfServiceUrl("这是第一版")
                //版本号
                .version("1.0.0").build();
    }
}

TestController.java

package com.example.springbootswagger.controller;

import com.example.springbootswagger.req.AddReq;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

@RestController
@Api(tags = {"测试接口类"}, hidden = true)
@RequestMapping("/test")
public class TestController {

    @ApiOperation("GET请求,查询方法")
    @GetMapping("/query")
    public String query() {
        return "查询成功";
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "param1", value = "参数1", required = true),
            @ApiImplicitParam(name = "param2", value = "参数2", required = false)
    })
    @ApiOperation("PUT请求,添加方法")
    @PutMapping("/update")
    public String update(
            @RequestParam(required = true) String param1,
            @RequestParam(required = false) String param2) {
        return "更新成功";
    }

    @ApiOperation("POST请求,修改方法")
    @PostMapping("/add")
    public String add(@RequestBody AddReq addReq) {
        return "添加成功";
    }

    @ApiImplicitParam(name = "id", value = "用户ID", required = true)
    @ApiOperation("DELETE请求,删除方法")
    @DeleteMapping("/del")
    public String del(Long id) {
        return "删除成功";
    }
}

AddReq.java

package com.example.springbootswagger.req;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel("添加参数")
public class AddReq {

    @ApiModelProperty("名字")
    private String name;

    @ApiModelProperty("密码")
    private String password;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

SpringbootSwaggerApplication.java

package com.example.springbootswagger;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableSwagger2
@SpringBootApplication
public class SpringbootSwaggerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootSwaggerApplication.class, args);
    }

}

posted @ 2022-07-05 17:31  sum墨  阅读(131)  评论(0编辑  收藏  举报