SpringBoot集成Swagger2产生RESTful API接口文档

一、环境准备:

1. Windows 10

2. Maven 3.X

3. InterlliJ IDEA 2019

4. JDK 13(JDK1.8以上)

二、项目结构图:

 

 

三、详细代码部分:

1. Maven的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.study.module</groupId>
    <artifactId>mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatis</name>
    <description>Demo project for Spring Boot: ORM Framework Mybatis</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>

        <!--热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <!--MySQL数据库连接-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--阿里巴巴连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.22</version>
        </dependency>
        <!--实体类:Lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--swagger2 RESTful API接口文档-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>
    </dependencies>

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

</project>

2 application.yaml 项目配置文件

server:
  port: 8089
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/zero?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: root123456
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  mapper-locations: classpath:/mapper/*Dao.xml
  typeAliasesPackage: com.study.module.mybatis.entity

 

3. Mapper文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 3 <mapper namespace="com.study.module.mybatis.dao.UserDao">
 4 
 5     <resultMap type="com.study.module.mybatis.entity.User" id="UserMap">
 6         <result property="id" column="id" jdbcType="INTEGER"/>
 7         <result property="name" column="name" jdbcType="VARCHAR"/>
 8         <result property="password" column="password" jdbcType="VARCHAR"/>
 9     </resultMap>
10 
11     <!--查询单个-->
12     <select id="queryById" resultMap="UserMap">
13         select
14           id, name, password
15         from zero.user
16         where id = #{id}
17     </select>
18 
19     <!--查询指定行数据-->
20     <select id="queryAllByLimit" resultMap="UserMap">
21         select
22           id, name, password
23         from zero.user
24         limit #{offset}, #{limit}
25     </select>
26 
27     <!--通过实体作为筛选条件查询-->
28     <select id="queryAll" resultMap="UserMap">
29         select
30           id, name, password
31         from zero.user
32         <where>
33             <if test="id != null">
34                 and id = #{id}
35             </if>
36             <if test="name != null and name != ''">
37                 and name = #{name}
38             </if>
39             <if test="password != null and password != ''">
40                 and password = #{password}
41             </if>
42         </where>
43     </select>
44 
45     <!--新增所有列-->
46     <insert id="insert" keyProperty="id" useGeneratedKeys="true">
47         insert into zero.user(name, password)
48         values (#{name}, #{password})
49     </insert>
50 
51     <!--通过主键修改数据-->
52     <update id="update">
53         update zero.user
54         <set>
55             <if test="name != null and name != ''">
56                 name = #{name},
57             </if>
58             <if test="password != null and password != ''">
59                 password = #{password},
60             </if>
61         </set>
62         where id = #{id}
63     </update>
64 
65     <!--通过主键删除-->
66     <delete id="deleteById">
67         delete from zero.user where id = #{id}
68     </delete>
69 
70 </mapper>
View Code

 

4. Dao 数据库操作文件

 1 package com.study.module.mybatis.dao;
 2 
 3 import com.study.module.mybatis.entity.User;
 4 import org.apache.ibatis.annotations.Mapper;
 5 import org.apache.ibatis.annotations.Param;
 6 
 7 import java.util.List;
 8 
 9 /**
10  * 用户表(用来测试代码生成插件EasyCode)(User)表数据库访问层
11  *
12  * @author makejava
13  * @since 2020-04-11 22:48:27
14  */
15 @Mapper
16 public interface UserDao {
17 
18     /**
19      * 通过ID查询单条数据
20      *
21      * @param id 主键
22      * @return 实例对象
23      */
24     User queryById(Integer id);
25 
26     /**
27      * 查询指定行数据
28      *
29      * @param offset 查询起始位置
30      * @param limit 查询条数
31      * @return 对象列表
32      */
33     List<User> queryAllByLimit(@Param("offset") int offset, @Param("limit") int limit);
34 
35 
36     /**
37      * 通过实体作为筛选条件查询
38      *
39      * @param user 实例对象
40      * @return 对象列表
41      */
42     List<User> queryAll(User user);
43 
44     /**
45      * 新增数据
46      *
47      * @param user 实例对象
48      * @return 影响行数
49      */
50     int insert(User user);
51 
52     /**
53      * 修改数据
54      *
55      * @param user 实例对象
56      * @return 影响行数
57      */
58     int update(User user);
59 
60     /**
61      * 通过主键删除数据
62      *
63      * @param id 主键
64      * @return 影响行数
65      */
66     int deleteById(Integer id);
67 
68 }
View Code
 实体类User
 1 package com.study.module.mybatis.entity;
 2 
 3 import io.swagger.annotations.ApiModel;
 4 import io.swagger.annotations.ApiModelProperty;
 5 
 6 import java.io.Serializable;
 7 
 8 /**
 9  * 用户表(用来测试代码生成插件EasyCode)(User)实体类
10  *
11  * @author makejava
12  * @since 2020-04-11 22:45:37
13  * <pre>
14  *  `@ApiModel`           参数Model对应的接口文档<br/>
15  *  `@ApiModelProperty`   参数Model对应属性的接口文档描述
16  * <pre/>
17  */
18 @ApiModel(value = "用户信息")
19 public class User implements Serializable {
20     private static final long serialVersionUID = -48812651257143828L;
21     /**
22      * 用户主键ID
23      */
24     @ApiModelProperty("用户ID")
25     private Integer id;
26     /**
27      * 用户名称
28      */
29     @ApiModelProperty("用户名称")
30     private String name;
31     /**
32      * 用户密码
33      */
34     @ApiModelProperty("用户登录密码")
35     private String password;
36 
37 
38     public Integer getId() {
39         return id;
40     }
41 
42     public void setId(Integer id) {
43         this.id = id;
44     }
45 
46     public String getName() {
47         return name;
48     }
49 
50     public void setName(String name) {
51         this.name = name;
52     }
53 
54     public String getPassword() {
55         return password;
56     }
57 
58     public void setPassword(String password) {
59         this.password = password;
60     }
61 
62     @Override
63     public String toString() {
64         return "User{" +
65                 "id=" + id +
66                 ", name='" + name + '\'' +
67                 ", password='" + password + '\'' +
68                 '}';
69     }
70 
71     public User() {
72     }
73 
74     public User(Integer id, String name, String password) {
75         this.id = id;
76         this.name = name;
77         this.password = password;
78     }
79 }
View Code

 

5. Service和ServiceImpl 业务层文件

① service
 1 package com.study.module.mybatis.service;
 2 
 3 import com.study.module.mybatis.entity.User;
 4 import java.util.List;
 5 
 6 /**
 7  * 用户表(用来测试代码生成插件EasyCode)(User)表服务接口
 8  *
 9  * @author makejava
10  * @since 2020-04-11 22:48:29
11  */
12 public interface UserService {
13 
14     /**
15      * 通过ID查询单条数据
16      *
17      * @param id 主键
18      * @return 实例对象
19      */
20     User queryById(Integer id);
21 
22     /**
23      * 查询多条数据
24      *
25      * @param offset 查询起始位置
26      * @param limit 查询条数
27      * @return 对象列表
28      */
29     List<User> queryAllByLimit(int offset, int limit);
30 
31     /**
32      * 新增数据
33      *
34      * @param user 实例对象
35      * @return 实例对象
36      */
37     User insert(User user);
38 
39     /**
40      * 修改数据
41      *
42      * @param user 实例对象
43      * @return 实例对象
44      */
45     User update(User user);
46 
47     /**
48      * 通过主键删除数据
49      *
50      * @param id 主键
51      * @return 是否成功
52      */
53     boolean deleteById(Integer id);
54 
55 }
View Code

 

② serviceImpl
 1 package com.study.module.mybatis.service.impl;
 2 
 3 import com.study.module.mybatis.entity.User;
 4 import com.study.module.mybatis.dao.UserDao;
 5 import com.study.module.mybatis.service.UserService;
 6 import org.springframework.stereotype.Service;
 7 
 8 import javax.annotation.Resource;
 9 import java.util.List;
10 
11 /**
12  * 用户表(用来测试代码生成插件EasyCode)(User)表服务实现类
13  *
14  * @author makejava
15  * @since 2020-04-11 22:48:29
16  */
17 @Service("userService")
18 public class UserServiceImpl implements UserService {
19     @Resource
20     private UserDao userDao;
21 
22     /**
23      * 通过ID查询单条数据
24      *
25      * @param id 主键
26      * @return 实例对象
27      */
28     @Override
29     public User queryById(Integer id) {
30         return this.userDao.queryById(id);
31     }
32 
33     /**
34      * 查询多条数据
35      *
36      * @param offset 查询起始位置
37      * @param limit 查询条数
38      * @return 对象列表
39      */
40     @Override
41     public List<User> queryAllByLimit(int offset, int limit) {
42         return this.userDao.queryAllByLimit(offset, limit);
43     }
44 
45     /**
46      * 新增数据
47      *
48      * @param user 实例对象
49      * @return 实例对象
50      */
51     @Override
52     public User insert(User user) {
53         this.userDao.insert(user);
54         return user;
55     }
56 
57     /**
58      * 修改数据
59      *
60      * @param user 实例对象
61      * @return 实例对象
62      */
63     @Override
64     public User update(User user) {
65         this.userDao.update(user);
66         return this.queryById(user.getId());
67     }
68 
69     /**
70      * 通过主键删除数据
71      *
72      * @param id 主键
73      * @return 是否成功
74      */
75     @Override
76     public boolean deleteById(Integer id) {
77         return this.userDao.deleteById(id) > 0;
78     }
79 }
View Code

 

6. Controller 控制层文件

① 第一个Controller
  1 package com.study.module.mybatis.controller;
  2 
  3 import com.study.module.mybatis.entity.User;
  4 import com.study.module.mybatis.service.UserService;
  5 import io.swagger.annotations.Api;
  6 import io.swagger.annotations.ApiImplicitParam;
  7 import io.swagger.annotations.ApiImplicitParams;
  8 import io.swagger.annotations.ApiOperation;
  9 import org.springframework.web.bind.annotation.*;
 10 import springfox.documentation.annotations.ApiIgnore;
 11 
 12 import javax.annotation.Resource;
 13 import java.util.Collections;
 14 import java.util.HashMap;
 15 import java.util.List;
 16 import java.util.Map;
 17 
 18 /**
 19  * 用户表(用来测试代码生成插件EasyCode)(User)表控制层
 20  * <pre>
 21  *     swagger2接入SpringBoot的学习示例网址:https://www.jb51.net/article/143533.htm
 22  *      1. 此controller访问的地址:例如 http://localhost:8089/user/selectAll
 23  *      2. 当前Controller的swaggerUI2文档:http://localhost:8089/swagger-ui.html#/
 24  * <pre/>
 25  * @author Drew
 26  * @since 2020-04-11 22:48:30
 27  */
 28 @Api(tags = "1.用户信息CURD操作", value = "")
 29 @RestController
 30 @RequestMapping("user")
 31 public class UserController {
 32     /**
 33      * 服务对象
 34      */
 35     @Resource
 36     private UserService userService;
 37 
 38     /**
 39      * 通过主键查询单条数据 {`@ApiIgnore` 使用该注解忽略这个API【即:在 swagger UI 文档中不会显示此接口】}
 40      *
 41      * @param id 主键
 42      * @return 单条数据
 43      */
 44     @ApiIgnore
 45     @GetMapping("selectOne/{id}")
 46     public User selectOne(@PathVariable("id") Integer id) {
 47         return this.userService.queryById(id);
 48     }
 49 
 50     @ApiOperation(value = "获取所有用户", notes = "get all user limit 10")
 51     @RequestMapping(value = "/selectAll", method = RequestMethod.GET)
 52     public List<User> selectAll() {
 53         return this.userService.queryAllByLimit(0, 10);
 54     }
 55 
 56     @ApiOperation(value = "根据用户ID查询用户信息", notes = "get user by ID")
 57     @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer", paramType = "path",
 58             defaultValue = "1")
 59     @RequestMapping(value = "selectById/{id}", method = RequestMethod.GET)
 60     public User selectById(@PathVariable("id") Integer id) {
 61         return this.userService.queryById(id);
 62     }
 63 
 64     /**
 65      * ====================== >>>> 更行指定用户的信息
 66      *
 67      * @return 所有的用户信息
 68      */
 69     private Map<Integer, User> userData() {
 70         Map<Integer, User> users = Collections.synchronizedMap(new HashMap<>(100));
 71         List<User> userList = this.userService.queryAllByLimit(0, 100);
 72         for (User user : userList) {
 73             users.put(user.getId(), user);
 74         }
 75         return users;
 76     }
 77 
 78     @ApiOperation(value = "更新指定用户ID信息", notes = "update user info by id.")
 79     @ApiImplicitParams({
 80             @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path"),
 81             @ApiImplicitParam(name = "user", value = "用户实体信息", required = true, dataType = "User")
 82     })
 83     @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
 84     public String updateUser(@PathVariable Integer id, @RequestBody User user) {
 85         Map<Integer, User> users = this.userData();
 86         System.out.println("【更新前】所有的用户信息:\n" + users);
 87         User user1 = users.get(id);
 88         user1.setName(user.getName());
 89         user1.setPassword(user.getPassword());
 90         users.put(id, user1);
 91         System.out.println("【更新后】所有的用户信息:\n" + users);
 92         return "success";
 93     }
 94 
 95     @ApiOperation(value = "删除用户", notes = "根据url的ID,来删除指定的用户")
 96     @ApiImplicitParam(name = "id", value = "用户ID", required = true, defaultValue = "2", dataType = "Integer",
 97             paramType = "path")
 98     @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
 99     public String deleteUser(@PathVariable(value = "id") Integer id) {
100         Map<Integer, User> users = this.userData();
101         System.out.println("【删除前】所有的用户信息:\n" + users);
102         users.remove(id);
103         System.out.println("【删除后】所有的用户信息:\n" + users);
104         return "success";
105     }
106 
107     @ApiIgnore
108     @RequestMapping(value = "/hi", method = RequestMethod.GET)
109     public String jsonTest() {
110         return " hi you!";
111     }
112 
113 }
View Code
② 第二个controller
 1 package com.study.module.mybatis.controller;
 2 
 3 import com.study.module.mybatis.entity.User;
 4 import io.swagger.annotations.Api;
 5 import io.swagger.annotations.ApiImplicitParam;
 6 import io.swagger.annotations.ApiImplicitParams;
 7 import io.swagger.annotations.ApiOperation;
 8 import org.springframework.web.bind.annotation.*;
 9 
10 import java.util.*;
11 
12 /**
13  * 用户表(用来测试代码生成插件EasyCode)(User)表控制层
14  * <pre>
15  *     swagger2接入SpringBoot的学习示例网址:https://www.jb51.net/article/143533.htm
16  *      1. 此controller访问的地址:例如 http://localhost:8089/users
17  *      2. 当前Controller的swaggerUI2文档:http://localhost:8089/swagger-ui.html#/
18  * <pre/>
19  * @author Drew
20  * @since 2020-04-19 09:00:45
21  */
22 @Api(tags = "2.用户信息CURD操作", value = "")
23 @RestController
24 @RequestMapping(value = "/users")
25 public class UserDetailController {
26     /**
27      * 数据准备
28      */
29     static Map<Integer, User> users = Collections.synchronizedMap(new HashMap<>());
30 
31     static {
32         users.put(1, new User(1, "drew1", "drew1"));
33         users.put(2, new User(2, "drew2", "drew2"));
34         users.put(3, new User(3, "drew3", "drew3"));
35         users.put(4, new User(4, "drew4", "drew4"));
36         users.put(5, new User(5, "drew5", "drew5"));
37         users.put(6, new User(6, "drew6", "drew6"));
38     }
39 
40     @ApiOperation(value = "获取用户列表", notes = "获取所有的用户信息")
41     @RequestMapping(value = {""}, method = RequestMethod.GET)
42     public List<User> getUserList() {
43         return new ArrayList<>(users.values());
44     }
45 
46     @ApiOperation(value = "创建用户", notes = "根据User对象创建用户")
47     @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
48     @RequestMapping(value = "", method = RequestMethod.POST)
49     public String postUser(@RequestBody User user) {
50         users.put(user.getId(), user);
51         return "success";
52     }
53 
54     @ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息")
55     @ApiImplicitParam(name = "id", defaultValue = "3", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
56     @RequestMapping(value = "/{id}", method = RequestMethod.GET)
57     public User getUser(@PathVariable Integer id) {
58         return users.get(id);
59     }
60 
61     @ApiOperation(value = "更新用户详细信息", notes = "根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
62     @ApiImplicitParams({
63             @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path"),
64             @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
65     })
66     @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
67     public String putUser(@PathVariable Integer id, @RequestBody User user) {
68         User u = new User(id, user.getName(), user.getPassword());
69         System.out.println("【更新前】所有的用户信息:\n" + users);
70         users.put(id, u);
71         System.out.println("【更新后】所有的用户信息:\n" + users);
72         return "success";
73     }
74 
75     @ApiOperation(value = "删除用户", notes = "根据url的id来指定删除对象")
76     @ApiImplicitParam(name = "id", defaultValue = "1", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
77     @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
78     public String deleteUser(@PathVariable Integer id) {
79         System.out.println("【删除前】所有的用户信息:\n" + users);
80         users.remove(id);
81         System.out.println("【删除后】所有的用户信息:\n" + users);
82         return "success";
83     }
84 }
View Code

 

7. Swagger 配置类

 1 package com.study.module.mybatis.config;
 2 
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.Configuration;
 5 import springfox.documentation.builders.ApiInfoBuilder;
 6 import springfox.documentation.builders.PathSelectors;
 7 import springfox.documentation.builders.RequestHandlerSelectors;
 8 import springfox.documentation.service.ApiInfo;
 9 import springfox.documentation.service.Contact;
10 import springfox.documentation.spi.DocumentationType;
11 import springfox.documentation.spring.web.plugins.Docket;
12 import springfox.documentation.swagger2.annotations.EnableSwagger2;
13 
14 /**
15  * Swagger启动配置类
16  *
17  * @author Drew
18  * @date 2020年4月19日 09点00分
19  */
20 @Configuration
21 @EnableSwagger2
22 public class SwaggerConfiguration {
23 
24     /**
25      * swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
26      *
27      * @return 配型swagger2接口文档的摘要
28      */
29     @Bean
30     public Docket createRestfulApi() {
31         return new Docket(DocumentationType.SWAGGER_2)
32                 //调用apiInfo方法,创建一个ApiInfo实例,里面是展示在文档页面信息内容
33                 .apiInfo(apiInfo())
34                 .pathMapping("/")
35                 .select()
36                 //暴露接口地址的包路径  例如:com.lance.learn.springbootswagger.controller
37                 .apis(RequestHandlerSelectors.basePackage("com.study.module.mybatis.controller"))
38                 .paths(PathSelectors.any())
39                 .build();
40     }
41 
42     /**
43      * 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
44      *
45      * @return Swagger2 配置的RESTful Api 信息
46      */
47     private ApiInfo apiInfo() {
48         return new ApiInfoBuilder()
49                 // 接口文档标题
50                 .title("SpringBoot-Swagger2-Mybatis-Demo")
51                 // 接口文档描述
52                 .description("API Description: 用于敏捷开发 >>> Spring Boot 测试使用 Swagger2 构建RESTful API")
53                 // 服务条款网址
54                 .termsOfServiceUrl("http://localhost/")
55                 // 接口文档维护联系人(创建人)
56                 .contact(new Contact("Drew", "http://www.baidu.com", "1234567890@qq.com"))
57                 // 接口文档的版本号
58                 .version("1.0.0")
59                 .build();
60     }
61 }
View Code

 8. Spring Boot 启动类 

package com.study.module.mybatis;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author Drew
 */
@SpringBootApplication
@MapperScan(value = "com.study.module.mybatis.dao")
public class MybatisApplication {

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

}

 

四、结果展示:

swagger2 文档结构展示

 

posted @ 2020-04-19 13:22  superdrew  阅读(450)  评论(1编辑  收藏  举报