SpringBoot集成Swagger2

通过idea搭建简单的环境整合SpringBoot + Mysql + Mybatis + Swagger,用于介绍Swagger整合 SpringBoot的所有流程。

项目环境

(1)JDK1.8及其以上(注意必须是1.8及以上版本版本)

(2)Spring 5.1.6

(3)Mybatis 3.5.1

Spring MVC集成springfox-swagger2构建Restful API

Maven依赖

(1)springfox-swagger2

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

(2)springfox-swagger-ui

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

(3)guava

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>20.0</version>
</dependency>

(4)mapstruct-jdk8

<!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct-jdk8 -->
<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct-jdk8</artifactId>
    <version>1.2.0.Final</version>
</dependency>

(5) Jackson

  -- jackson-core  
  -- jackson-databind  
  -- jackson-annotations
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.8</version>
</dependency>

集成配置步骤

本节内容主要介绍环境搭建及Swagger整合,Swagger的具体应用将于下一章节详细介绍,创建完成目录结构如下

 (1)idea创建springboot环境

  --》File--》New--》Project

--》填写Artifact  

--》勾选Dependecies

--》指定项目存储路径

--》配置application.properties文件
#tomcat端口
server.port=8088
#数据连接
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/swaggerdemo?serverTimezone=UTC
spring.datasource.username=xxx
spring.datasource.password=xxx
 
#Mybatis扫描
mybatis.mapper-locations=classpath*:mapperxml/*.xml
--》完成

(2)pom.xml配置Swagger所需依赖

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>swaggerdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>swaggerdemo</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.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
 
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jetbrains</groupId>
            <artifactId>annotations</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
 
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
 
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
 
        <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>20.0</version>
        </dependency>
 
        <!-- https://mvnrepository.com/artifact/org.mapstruct/mapstruct-jdk8 -->
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-jdk8</artifactId>
            <version>1.2.0.Final</version>
        </dependency>
 
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.8</version>
        </dependency>
 
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>

(3)创建数据库及数据表

3.1 创建表插入测试数据

/*
Navicat MySQL Data Transfer
Source Server         : StudyTestDemo
Source Server Version : 50721
Source Host           : 127.0.0.1:3306
Source Database       : swaggerdemo
Target Server Type    : MYSQL
Target Server Version : 50721
File Encoding         : 65001
Date: 2019-04-25 23:47:16
*/
 
SET FOREIGN_KEY_CHECKS=0;
 
-- ----------------------------
-- Table structure for userinfo
-- ----------------------------
DROP TABLE IF EXISTS `userinfo`;
CREATE TABLE `userinfo` (
  `user_id` int(10) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `user_account` varchar(255) NOT NULL COMMENT '账号',
  `user_password` varchar(255) NOT NULL COMMENT '用户密码',
  `user_name` varchar(255) DEFAULT '' COMMENT '用户名',
  `user_age` int(10) DEFAULT NULL COMMENT '用户年龄',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
 
-- ----------------------------
-- Records of userinfo
-- ----------------------------
INSERT INTO `userinfo` VALUES ('1', 'test', '123', 'nihao', '12');
INSERT INTO `userinfo` VALUES ('2', 'test2', '123', 'test2', '435');
INSERT INTO `userinfo` VALUES ('3', 'test3', '123', 'test2', '435');
INSERT INTO `userinfo` VALUES ('4', 'test4', '123', 'test2', '435');
INSERT INTO `userinfo` VALUES ('5', 'test5', '123', 'test2', '435');

4)创建一个访问接口
4.1 创建Model

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
 
@ApiModel(value = "用户Model")
public class Userinfo {
 
    @ApiModelProperty(
            value = "用户id",
            name = "id",
            dataType = "Integer",
            required = true
    )
    private Integer userId;
 
    @ApiModelProperty(
            value = "账号",
            name = "userAccount",
            dataType = "String",
            required = true
    )
    private String userAccount;
 
    @ApiModelProperty(
            value = "密码",
            name = "userPassword",
            dataType = "String",
            required = true
    )
    private String userPassword;
 
    @ApiModelProperty(
            value = "用户名",
            name = "userName",
            dataType = "String",
            required = false
    )
    private String userName;
 
    @ApiModelProperty(
            value = "年龄",
            name = "userAge",
            dataType = "Integer"
    )
    private Integer userAge;
 
    ...
        getter  And Setter 
    ...
}

4.2 创建Dao层

import com.example.swaggerdemo.model.Userinfo;
import com.example.swaggerdemo.model.UserinfoExample;
import java.util.List;
 
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
 
public interface UserinfoMapper {
 
    Userinfo selectByPrimaryKey(Integer userId);
}

4.3 创建xml映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.swaggerdemo.mapper.UserinfoMapper" >
  <resultMap id="BaseResultMap" type="com.example.swaggerdemo.model.Userinfo" >
    <id column="user_id" property="userId" jdbcType="INTEGER" />
    <result column="user_account" property="userAccount" jdbcType="VARCHAR" />
    <result column="user_password" property="userPassword" jdbcType="VARCHAR" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <result column="user_age" property="userAge" jdbcType="INTEGER" />
  </resultMap>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select * from userinfo
    where user_id = #{userId,jdbcType=INTEGER}
  </select>
</mapper>

4.4 添加Server层

import com.example.swaggerdemo.model.Userinfo;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
/**
 * Created by Anna. on 2019/4/24 0024.
 */
public interface UserinfoService {
    Userinfo selectUserinfoById(Integer id);
}
import com.example.swaggerdemo.mapper.UserinfoMapper;
import com.example.swaggerdemo.model.Userinfo;
import com.example.swaggerdemo.service.UserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
/**
 * Created by Anna. on 2019/4/24 0024.
 */
@Service("userinfoService")
public class UserServiceImpl implements UserinfoService {
 
    @Autowired
    private UserinfoMapper userinfoMapper;
 
    public Userinfo selectUserinfoById(Integer id) {
        return userinfoMapper.selectByPrimaryKey(id);
    }
}

4.5 创建Controller层

import com.example.swaggerdemo.model.Userinfo;
import com.example.swaggerdemo.service.UserinfoService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
/**
 * Created by Anna. on 2019/4/24 0024.
 */
@Api(value = "测试AIP", tags = "Swagger测试接口API")
@RestController
public class UserInfoController {
 
    @Autowired
    private UserinfoService userinfoService;
 
    @ApiOperation(
            value = "根据ID查找用户信息",
            notes = "查询数据库中某个用户的详细信息",
            response = Userinfo.class,
            httpMethod = "GET"
    )
    @ApiImplicitParams(
            @ApiImplicitParam(name = "id", value = "用户ID", paramType = "path", required = true)
    )
    @RequestMapping(value="/select/{id}",method = RequestMethod.GET)
    public Userinfo selectUserinfoByid(@PathVariable("id") Integer id){
        Userinfo userinfo = userinfoService.selectUserinfoById(id);
        return userinfo != null ? userinfo : null;
    }
 
}

4.5 添加Swagger配置文件

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
 
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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
 
//@EnableWebMvc
@EnableSwagger2 // 启动swagger
@Configuration  // 自劢在本类上下文加载一些环境变量信息
@ComponentScan(basePackages ={"com.example.swaggerdemo.controller"}) // 设置扫描包
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
 
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("XXX项目-主业务模块API")
                .description("XXX项目-主业务模块API-描述信息")
                .termsOfServiceUrl("http://test.com/swagger")
                .contact(new Contact("", "", ""))
                .version("1.1.0")
                .build();
    }
}

完成,启动项目访问,http://localhost:8088/swagger-ui.html

以上就是SpringBoot集成Swagger2的全部流程,操作简单,按照流程过一遍就好,如果对大家有帮助,谢谢点个关注,点个赞。

gif5新文件(1).gif

640.png


TopJavaer
291 声望64 粉丝