SpringBoot整合Swagger生成接口文档

一、简介

Swagger是一个功能强大的API框架,它支持在线文档的查看以及在线文档的测试,方便我们前后端开发人员对接。Swagger使用起来也很简单,只需要加入swagger对应的依赖以及在controller类以及方法中加入相应的注解说明,swagger就会帮我们自动生成API接口文档。

本文主要通过一个简单的模拟增删查改功能实现springboot整合swagger2生成Restful 接口文档。

二、新建springboot_swagger项目

【a】swagger依赖:

<!--Swagger2依赖-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.2.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.2.2</version>
</dependency>

具体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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.springboot.wsh</groupId>
	<artifactId>springboot_swagger</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springboot_swagger</name>
	<description>使用Swagger生成API文档</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.10.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!--Swagger2依赖-->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.2.2</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.2.2</version>
		</dependency>
	</dependencies>

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


</project>

【b】新建User实体类

package com.springboot.wsh.entity;

import java.io.Serializable;

/**
 * @Title: User
 * @ProjectName springboot_swagger
 * @Description: 用户实体类
 * @Author WeiShiHuai
 * @Date 2018/9/29 17:58
 */
public class User implements Serializable {

    private Long id;
    private String username;
    private String password;

    public User(Long id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

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

【c】新建SwaggerConfiguration配置类

在配置类上加上注解@EnableSwagger2、@Configuration,主要配置一些apiInfo信息(标题、描述、版本号等)以及配置Docket(文档类型、api信息、生成接口文档需要扫描的包等)

@EnableSwagger2:开启swagger功能

package com.springboot.wsh.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;

/**
 * @Title: SwaggerConfiguration
 * @ProjectName springboot_swagger
 * @Description: Swagger配置类
 * @Author WeiShiHuai
 * @Date 2018/9/29 17:36
 * <p>
 * 说明: Swagger2可以帮助我们快速生成API接口文档,方便我们进行调试。只需要在对应的Controller方法上加上一些注解即可,
 * 访问地址: http://主机名称:端口号/swagger-ui.html  ( 如:http://localhost:8080/swagger-ui.html)
 */
//@Configuration表示这是一个配置类
@Configuration
//@EnableSwagger2: 开启Swagger2生成api文档功能
@EnableSwagger2
public class SwaggerConfiguration {

    /**
     * 配置api信息(标题、描述、版本号等)
     *
     * @return api信息
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("使用Swagger2生成API接口文档")   //标题
                .description("swagger2提供了强大的接口文档功能,方便接口调试")  //描述信息
                .version("1.0")   //版本号
                .termsOfServiceUrl("https://blog.csdn.net/Weixiaohuai")  //服务URL地址
                .build();
    }

    /**
     * 配置Docket对象,配置一些信息(文档类型、api信息、生成接口文档需要扫描的包等)
     *
     * @return Docket对象
     */
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)  //指定文档类型
                .apiInfo(apiInfo()) //指定Api相关信息
                .select()  //选择那些路径和api会生成文档
                .apis(RequestHandlerSelectors.basePackage("com.springboot.wsh.controller"))  //指定生成文档扫描的包
                .paths(PathSelectors.any())  //指定对所有路径进行监控
                .build();

    }

}

【d】新建UserController

这个类主要部分是swagger2部分,增删查改功能只是模拟而已。

package com.springboot.wsh.controller;

import com.springboot.wsh.entity.User;
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.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;

/**
 * @Title: UserController
 * @ProjectName springboot_swagger
 * @Description: 用户Controller
 * @Author WeiShiHuai
 * @Date 2018/9/29 17:49
 * <p>
 * 说明: Swagger的好处
 * 1. 简单方便、自动生成文档、调试方便、方便前后端对接
 * 2. 减少前后台的研发沟通成本,相对文档化的资源,支持简单的手工测试
 */
@RestController
@RequestMapping("/user")
//@Api: 标识该Controller的功能
@Api("用户-相关服务Api")
public class UserController {

    private static List<User> userList = new ArrayList<>();

    static {
        userList.add(new User(1L, "zhangsan", "123456"));
        userList.add(new User(2L, "lisi", "654321"));
    }

    @GetMapping("/getUserList")
    //@ApiOperation: 标识该接口的作用
    @ApiOperation(value = "获取用户列表信息", notes = "获取用户列表信息", httpMethod = "GET")
    public List<User> getUserList() {
        return userList;
    }

    @GetMapping("/getUserInfo/{id}")
    @ApiOperation(value = "根据id获取用户信息", notes = "根据id获取用户信息", httpMethod = "GET")
    //@ApiImplicitParam: 标识接口中参数的类型、是否必填、描述等
    @ApiImplicitParam(name = "id", value = "用户id", dataType = "Long", paramType = "path", required = true)
    public User getUserInfo(@PathVariable("id") Long id) {
        return userList.get(id.intValue());
    }

    @GetMapping("/getUserById")
    @ApiOperation(value = "根据id获取用户信息2", notes = "根据id获取用户信息2", httpMethod = "GET")
    @ApiImplicitParam(name = "id", value = "用户id", dataType = "Long", paramType = "query", required = true)
    public User getUserById(@RequestParam("id") Long id) {
        return userList.get(id.intValue());
    }

    @PostMapping("/saveUser")
    @ApiOperation(value = "保存用户信息", notes = "保存用户信息", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "用户实体信息", required = true, paramType = "body", dataType = "User")
    })
    public String saveUser(@RequestBody User user) {
        userList.add(user);
        return "save user success!!";
    }

    @PostMapping("/updateUser/{id}")
    @ApiOperation(value = "更新用户信息", notes = "更新用户信息", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", required = true, paramType = "path", dataType = "Long"),
            @ApiImplicitParam(name = "user", value = "用户实体信息", required = true, paramType = "body", dataType = "User")
    })
    public String updateUser(@PathVariable("id") Long id, @RequestBody User user) {
        userList.set(id.intValue(), user);
        return "update user success!!";
    }


    @PostMapping("/deleteUser/{id}")
    @ApiOperation(value = "根据用户id删除用户信息", notes = "根据用户id删除用户信息", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", required = true, paramType = "path", dataType = "Long")
    })
    public String deleteUser(@PathVariable("id") Long id) {
        userList.remove(id.intValue());
        return "delete user success";
    }

    @ApiOperation(value = "批量删除用户信息", notes = "批量删除用户信息", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "pkids", dataType = "List", required = true, value = "主键")
    })
    @PostMapping(value = "/deleteByMulti")
    public String deleteByMulti(@RequestBody List<String> pkids) {
        //批量删除逻辑
        return "deleteByMulti success";
    }

    //@ApiIgnore: 忽略该接口,不生成该接口对应的文档
    @ApiIgnore
    @GetMapping(value = "/hello")
    public String hello() {
        return "hello";
    }

}

【e】一些常用注解说明

 @Api: 标识该Controller的功能

 @ApiOperation: 标识该接口的作用 如:

@ApiOperation(value = "获取用户列表信息", notes = "获取用户列表信息", httpMethod = "GET")

@ApiImplicitParam: 标识接口中参数的类型、是否必填、描述等 如:

@ApiImplicitParam(name = "id", value = "用户id", dataType = "Long", paramType = "path", required = true)
@ApiImplicitParams:可以配置多个@ApiImplicitParam,如:
@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "用户id", required = true, paramType = "path", dataType = "Long"),
        @ApiImplicitParam(name = "user", value = "用户实体信息", required = true, paramType = "body", dataType = "User")
})
@ApiIgnore: 忽略该接口,不生成该接口对应的文档,如
@ApiIgnore
    @GetMapping(value = "/hello")
    public String hello() {
        return "hello";
    }

三、启动项目

启动完项目,浏览器访问: http://localhost:8080/swagger-ui.html

如图可以看到,swagger已经帮我们生成了接口文档。我们可以对这些接口进行简单的测试。

四、补充说明

@ApiImplicitParam】接口中参数说明:

属性 取值 说明
paramType   查询参数类型
  path 以地址的形式提交数据, @PathVariable()修饰的参数
  query 直接跟参数完成自动映射赋值,@RequestParam()修饰的参数
  body 以流的形式提交 仅支持POST,@RequestBody修饰的参数
  header 参数在request headers 里边提交
  form 以form表单的形式提交 仅支持POST
dataType Object 参数的数据类型 
  Long  
  String  
  List  
name   接收参数名
value   接收参数的意义描述
required true 参数是否必填
  false  
     

示例:

【a】paramType="path"

@ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", required = true, paramType = "path", dataType = "Long")
    })
    public String deleteUser(@PathVariable("id") Long id) {}

【b】paramType="query"

@ApiImplicitParam(name = "id", value = "用户id", dataType = "Long", paramType = "query", required = true)
    public User getUserById(@RequestParam("id") Long id) {
        }

【c】paramType="body"

 @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "用户实体信息", required = true, paramType = "body", dataType = "User")
    })
    public String saveUser(@RequestBody User user) {}

五、总结

至此,springboot整合swagger生成api接口文档已经实现了。在微服务中,各个服务都可以整合swagger,这样我们就可以测试每一个微服务单元的接口,非常方便。本文是作者对swagger的一些总结,仅供大家参考,一起学习一起进步。

猜你喜欢

转载自blog.csdn.net/Weixiaohuai/article/details/82915372