SpringBoot整合Swagger

Swagger官网:https://swagger.io

Swagger官方文档:https://swagger.io/docs

在没有使用Swagger之前,我们在做前后端分离项目或接口项目时,总是需要再写一份接口文档给调用方,每次更新代码之后,可能还需要再更新接口文档,有时候过于忙碌甚至来不及更新,麻烦了自己的同时,可能还会惹来别人的抱怨。

在这种情况下,使用Swagger自动生成文档就给我们带来了很多方便,只需要在编写代码的时候,加上注解和描述即可,代码完成了,文档也自动生成了。

本文即记录了SpringBoot整合Swagger生成接口文档的过程。下面直接上代码:

开发工具:idea

技术栈:springboot、swagger

下图为项目结构:

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.hongke</groupId>
    <artifactId>swaggerDemo</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>
    <name>swaggerDemo</name>
    <description>this is swagger demo</description>

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

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.12.RELEASE</version>
    </parent>

    <dependencies>
        <!--引入spring-boot-starter-web Jar包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--引入swagger Jar包-springfox-swagger2-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!--引入swagger Jar包-springfox-swagger-ui-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

        <!--引入lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

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

</project>

application.yml:

server:
  port: 9091

SwaggerConfig配置类:

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

/**
 * @author chengjunyu
 * @classname SwaggerConfig
 * @description swagger配置类
 * @date 2020/7/20 10:35
 */
@Configuration
//启动swagger
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.hongke.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("宏科信息")
                .description("this is interface doc")
                .version("V1.0")
                .build();
    }

}

User实体类:

package com.hongke.entity;

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

/**
 * @author chengjunyu
 * @classname User
 * @description 用户实体类
 * @date 2020/7/20 11:21
 */
@Data
@ApiModel
public class User {

    @ApiModelProperty(value = "用户ID")
    private Integer id;

    @ApiModelProperty(value = "用户名称")
    private String name;

    @ApiModelProperty(value = "用户性别")
    private String sex;

    @ApiModelProperty(value = "用户年龄")
    private Integer age;

    public User(Integer id, String name, String sex, Integer age) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.age = age;
    }
}

controller层: 

package com.hongke.controller;

import com.hongke.Result.ResultInfo;
import com.hongke.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author chengjunyu
 * @classname UserController
 * @description 用戶controller层
 * @date 2020/7/20 10:33
 */
@RestController("/user")
@Api(tags = "用户管理操作")
public class UserController {

    /**
     * @description 根据条件查询用户列表
     * @author chengjunyu
     * @date 2020/7/20 10:48
     * @param user
     * @return com.hongke.Result.ResultInfo
     **/
    @ApiOperation(value = "根据条件查询用户列表")
    @GetMapping("/getList")
    public ResultInfo getUserList(User user) {
        User user1 = new User(1, "aaa", "男", 20);
        User user2 = new User(2, "bbb", "女", 21);
        User user3 = new User(3, "ccc", "男", 22);
        User user4 = new User(4, "ddd", "女", 23);
        User user5 = new User(5, "eee", "男", 24);
        List<User> userList = new ArrayList<>();
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        userList.add(user5);
        return ResultInfo.success(userList);
    }

    /**
     * @description 新增用户信息
     * @author chengjunyu
     * @date 2020/7/20 10:48
     * @param user
     * @return com.hongke.Result.ResultInfo
     **/
    @PostMapping("/save")
    @ApiOperation(value = "新增用户信息")
    public ResultInfo addUser(@RequestBody(required = true) User user) {
        return ResultInfo.success(user);
    }

    
    @PostMapping("/update")
    @ApiOperation(value = "修改用户信息", notes = "修改用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true),
            @ApiImplicitParam(name = "age", value = "年龄", required = true
            )
    })
    public ResultInfo updateUser(@RequestParam("id") Integer id, @RequestParam("age") Integer age) {
        User user = new User(1, "aaa", "男", 22);
        user.setId(id);
        user.setAge(age);
        return ResultInfo.success(user);
    }


    /**
     * @description 删除用户信息
     * @author chengjunyu
     * @date 2020/7/20 10:48
     * @param id
     * @return com.hongke.Result.ResultInfo
     **/
    @GetMapping("/delete")
    @ApiOperation(value = "删除用户信息", notes = "根据人员ID删除指定人员信息")
    @ApiImplicitParam(name = "id", value = "人员ID", required = true)
    public ResultInfo deleteUser(@RequestParam(value = "id", required = true) Integer id) {
        return ResultInfo.success("删除成功", null);
    }
}

ResultInfo返回信息:

package com.hongke.Result;

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

/**
 * @author chengjunyu
 * @classname ResultInfo
 * @description 返回结果
 * @date 2020/7/20 11:34
 */
@Data
@ApiModel
public class ResultInfo {

    @ApiModelProperty(value = "返回码,200为正确,其余为错误")
    private Integer code;
    @ApiModelProperty(value = "返回信息")
    private String message;
    @ApiModelProperty(value = "返回对象")
    private Object object;

    private ResultInfo(Integer code, String message, Object object) {
        this.code = code;
        this.message = message;
        this.object = object;
    }

    public static ResultInfo success(String message) {
        return new ResultInfo(200, message, null);
    }

    public static ResultInfo success(Object object) {
        return new ResultInfo(200, "success", object);
    }

    public static ResultInfo success(String message, Object object) {
        return new ResultInfo(200, message, object);
    }

    public static ResultInfo failure(String message) {
        return new ResultInfo(999, message, null);
    }

}

启动类:

package com.hongke;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author chengjunyu
 * @classname SwaggerApplication
 * @description 启动类
 * @date 2020/7/20 10:26
 */
@SpringBootApplication
public class SwaggerApplication {

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

结果如下:

在上面文档中生成了三个方法,都是我在项目中通过添加Swagger的注解后生成的。如果你不需要某接口生成文档,只需要在加@ApiIgnore注解即可。另外,如果请求参数在url上,@ApiImplicitParam 上加paramType = “path” 即可。至此,Springboot整合Swagger结束。

补充:

Swagger注解说明:

@Api:用来修饰整个类,描述Controller的作用,加在Controller层的类的外部
@ApiOperation:描述一个类的一个方法,或者说一个接口,加在方法上
@ApiParam:描述单个参数描述 
@ApiModel:用对象来接收参数
@ApiModelProperty:用对象接收参数时,描述对象中的字段
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiIgnore:使用该注解忽略这个API
@ApiError :发生错误返回的信息
@ApiImplicitParam:一个请求参数
@ApiImplicitParams:多个请求参数,内部每个请求参数再用@ApiImplicitParam修饰

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值