项目开发常采用前后端分离的方式。前后端通过API进行交互,在Swagger UI中,前后端人员能够直观预览并且测试API,方便前后端人员同步开发。

在SpringBoot中集成swagger,步骤如下:

1.项目开始当然离不了的就是pom文件了,下面的依赖添加到Maven项目的pom.xml文件中。springfox-swagger2组件帮助我们自动生成描述API的json文件,而springfox-swagger-ui组件就是将这个json文件解析出来,用一种更友好的方式呈现出来。另外我这边操作数据库运用了mybatis-puls省去一部分的代码问题,有想了解mybatis-puls的可以去看我的上一篇文章https://www.cnblogs.com/WrBug/p/10177770.html

<name>springboot-mybatis-puls—swagger</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.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>
<mysql.version>5.1.24</mysql.version>
<swagger2.version>2.7.0</swagger2.version>
<plexus-build-api.version>0.0.7</plexus-build-api.version>
<jackson-module-scala.version>2.9.1</jackson-module-scala.version>
<commons-lang.version>3.1</commons-lang.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>${swagger2.version}</version>
</dependency> <dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger2.version}</version>
</dependency>
<!----> <dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> <dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatisplus-spring-boot-starter</artifactId>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.1.8</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency> <!-- springboot整合mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency> </dependencies> <!--
mybatis-puls 的插件代码生成器
-->
<build>
<finalName>mybatis_puls</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>cn.pubinfo</groupId>
<artifactId>mp-generator</artifactId>
<version>1.01-SNAPSHOT</version>
<configuration>
<tables>
<table>user</table><!--数据库表名-->
</tables>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>

2.添加application.yml文件

server:
port: 8080
servlet:
context-path: /api
spring:
datasource:
url: jdbc:mysql://localhost:3306/数据库名称?useUnicode=true&characterEncoding=utf8
username: ****
password: ******
driver-class-name: com.mysql.jdbc.Driver
mybatis-plus:
mapper-locations: classpath:/mapper/*Mapper.xml
type-aliases-package: cn.api.model

3.添加Swaager的配置类

package cn.api.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.async.DeferredResult;
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; /**
* Swagger配置
*
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig { @Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.genericModelSubstitutes(DeferredResult.class)
.useDefaultResponseMessages(false)
.forCodeGeneration(true)
.apiInfo(apiInfo())
.pathMapping("/")// base,最终调用接口后会和paths拼接在一起
.select()
.apis(RequestHandlerSelectors.basePackage("cn.api.controller")) //这块是关键哦,最后你的接口能不能显示出来都在这呢
.paths(PathSelectors.any())
.build();
} private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger构建api文档")
.description("简单优雅的restful风格")
.termsOfServiceUrl("https://github.com/springfox/springfox-demos")
.version("1.0")
.build();
}
}
或者
@Configuration
@EnableSwagger2
public class SwaggerConfig {   @Resource
  private TypeResolver typeResolver
    @Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/")
.select()
.apis(RequestHandlerSelectors.basePackage("cn.*.controller"))
.paths(PathSelectors.any())
.build().apiInfo(new ApiInfoBuilder()
.title("swagger接口")
.description("swagger接口...")
.version("1.0")
.build());
          .additionalModels(typeResolver.resolve(OperateLog.class)); //解决没用到的实体类显示
    }

}

4.在需要暴露的API上添加需要在Swagger UI页面上当然要显示应用相关的介绍信息,生成API就是为了就是方便前后端人员同步开发。举个例子吧~

在Controller类上添加@API注解,说明该类的作用;该类下包含增删改查几个方法,给大家一个全面的示范,至于service、dao层的实现,留给大家自己发挥吧~主要是在方法上添加@ApiOperation,@ApiImplicitParam注解,作用是对方法以及参数的说明

package cn.api.controller;

import cn.api.service.UserService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import cn.api.model.User; import javax.annotation.Resource;
import java.util.List; /**
* @author kuancz
*/
@Api(tags = "用户表")
@RestController
@RequestMapping("/user")
public class UserController { @Resource
private UserService userService; /**
* 所有用户信息
*
*/
@GetMapping("/queryAll")
@ApiOperation(value = "获取集合", notes = "获取所有实体")
public List<User> queryUser() {
List<User> userList = userService.selectList(new EntityWrapper<>());
return userList;
} @GetMapping("/test")
@ApiOperation(value = "获取", notes = "测试用户")
@ApiImplicitParam(name = "name",value = "名字",required = true,dataType = "String",paramType = "query")
public List<User> getEmployee(@RequestParam String name) {
return userService.selectList(new EntityWrapper<User>().eq("name",name));
} /**
* 用户新增
*
* @param user 实体
*/
@PostMapping("/insert")
@ApiOperation(value = "增加", notes = "根据实体增加用户")
public Integer insert(@RequestBody User user) {
userService.insert(user);
return user.getId();
} @ApiOperation(value = "修改用户", notes = "根据实体更新用户")
@PatchMapping("/update")
public boolean update(@RequestBody User user) {
boolean update = userService.update(user,new EntityWrapper<>());
return update;
} @ApiOperation(value = "删除用户",notes = "根据id删除对应实体")
@DeleteMapping("/delete")
@ApiImplicitParam(name = "id",value = "id",required = true,dataType = "Integer",paramType = "query")
public boolean delete(@RequestParam Integer id) {
boolean del = userService.deleteById(id);
return del;
} @ApiOperation(value = "查询",notes = "根据ID获取用户")
@GetMapping("/getByid")
@ApiImplicitParam(name = "id",value = "id",required = true,dataType = "Integer",paramType = "query")
public User getByid(@RequestParam Integer id) {
User user = userService.selectById(id);
return user;
} }

5.启动SpringBoot项目,访问http:http://localhost:8080/api/swagger-ui.html#/页面,注意了,我这里是因为在application.properties配置了项目路径server.servlet.context-path=/api,所以才在上面的url加上/api,一般若无特殊的配置,直接访问http://localhost:8080/swagger-ui.html即可

springboot+mybatis-puls利用swagger构建api文档的更多相关文章

  1. springboot利用swagger构建api文档

    前言 Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件.本文简单介绍了在项目中集成swagger的方法和一些常见问题.如果想深入分析项目源码,了解更多内容,见参考资料. S ...

  2. springboot学习-jdbc操作数据库--yml注意事项--controller接受参数以及参数校验--异常统一管理以及aop的使用---整合mybatis---swagger2构建api文档---jpa访问数据库及page进行分页---整合redis---定时任务

    springboot学习-jdbc操作数据库--yml注意事项--controller接受参数以及参数校验-- 异常统一管理以及aop的使用---整合mybatis---swagger2构建api文档 ...

  3. 白话SpringCloud | 第十一章:路由网关(Zuul):利用swagger2聚合API文档

    前言 通过之前的两篇文章,可以简单的搭建一个路由网关了.而我们知道,现在都奉行前后端分离开发,前后端开发的沟通成本就增加了,所以一般上我们都是通过swagger进行api文档生成的.现在由于使用了统一 ...

  4. Spring Boot中使用Swagger2构建API文档

    程序员都很希望别人能写技术文档,自己却很不愿意写文档.因为接口数量繁多,并且充满业务细节,写文档需要花大量的时间去处理格式排版,代码修改后还需要同步修改文档,经常因为项目时间紧等原因导致文档滞后于代码 ...

  5. 【WebAPI No.4】Swagger实现API文档功能

    介绍: Swagger也称为Open API,Swagger从API文档中手动完成工作,并提供一系列用于生成,可视化和维护API文档的解决方案.简单的说就是一款让你更好的书写API文档的框架. 我们为 ...

  6. Swagger实现API文档功能

    介绍: wagger也称为Open API,Swagger从API文档中手动完成工作,并提供一系列用于生成,可视化和维护API文档的解决方案.简单的说就是一款让你更好的书写API文档的框架. 我们为什 ...

  7. 基于.NetCore3.1搭建项目系列 —— 使用Swagger做Api文档 (下篇)

    前言 回顾上一篇文章<使用Swagger做Api文档 >,文中介绍了在.net core 3.1中,利用Swagger轻量级框架,如何引入程序包,配置服务,注册中间件,一步一步的实现,最终 ...

  8. 在ASP.NET Core Web API上使用Swagger提供API文档

    我在开发自己的博客系统(http://daxnet.me)时,给自己的RESTful服务增加了基于Swagger的API文档功能.当设置IISExpress的默认启动路由到Swagger的API文档页 ...

  9. Core Web API上使用Swagger提供API文档

    在ASP.NET Core Web API上使用Swagger提供API文档   我在开发自己的博客系统(http://daxnet.me)时,给自己的RESTful服务增加了基于Swagger的AP ...

随机推荐

  1. JAVAEE第三周

    2.背景:看到Session时,感到很熟悉,毕竟涉及到过类似的编程,用得最多的地点就是保存客户端的信息和记录,比如说你已经登陆过某个网站,下次访问时不想要麻烦的重新登陆你就就可以使用这个机制.Sess ...

  2. Object.prototype.toString.call() 、 instanceof 以及 Array.isArray()判断数组的方法的优缺点

    1. Object.prototype.toString.call() 每一个继承 Object 的对象都有 toString 方法,如果 toString 方法没有重写的话,会返回 [Object ...

  3. 实训任务04 MapReduce编程入门

    实训任务04 MapReduce编程入门 1.实训1:画图mapReduce处理过程 使用有短句“A friend in need is a friend in deed”,画出使用MapReduce ...

  4. JVM CUP占用率过高排除方法,windows环境

    jdk自带的jvisualvm可以看到程序CPU使用率,但是无法确定具体的线程,想要确定到具体的线程需要借用到微软的Process Explorer 具体排除方法: 一:打开资源管理器,找到cup占用 ...

  5. xpath简单实用

    一.xpath 基本语法 /html /html/head/title 绝对路径(一层层的查找) /html//title 相对于当前节点 //title/./../.. . 当前节点 ..父节点 . ...

  6. JDBC-day1

    package cn.gzsxt.test; import java.sql.Connection;import java.sql.DatabaseMetaData;import java.sql.D ...

  7. 算数运算符& 关系运算符

    java中的算数运算符 + - * / % ++ -- + +: 加法运算符 - : 减法运算符 *: 乘法运算符 / : 除法运算符 注意: 除数不能为0,除数为0会报出异常 整数运算默认得到整数, ...

  8. MNIST机器学习入门

    "python: 3.5" # -*- coding: utf-8 -*-"""Created on Tue Oct 16 15:29:38 2018 ...

  9. sessionFactory中的openSession和getCurrentSession的一些注意事项

    今天进行Hibernate测试时遇到了一个问题 我在用sessionFactory生产seesion时出现了故障,使用getCurrentsesstion时产生异常: Exception in thr ...

  10. 学习小片段——thymeleaf入门

    1: 概述 thymeleaf是一个跟 Velocity.FreeMarker 类似的模板引擎,和以前学的jsp相近,但性能上无疑是比jsp好. 参考文档官方文档:https://www.thymel ...