项目开发常采用前后端分离的方式。前后端通过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. c# Expression 扩展

    一.简介 当查询比较复杂时,需要很多判断或者跨方法传递参数时使用 二.扩展类   public static class DynamicLinqExpressions { public static ...

  2. ACCESS 查询重复记录

    In (SELECT [全称] FROM [New14] As Tmp GROUP BY [全称],[账号],[银行] HAVING Count(*)>1  And [账号] = [New14] ...

  3. [图形学]VS2017中OpenGL的下载及安装中的异常

    1.放dll文件:C:\Windows\SysWOW64 或C:\Windows\windows32 2.lib和h:C:\Program Files (x86)\Microsoft Visual S ...

  4. 北航OO第一单元总结

    我本着公平公开公正的态度作出以下评价: 1.面向对象真的很修身养性 2.有一个好的身体非常重要 3.互相hack可以暴露人的阴暗面 好了,步入正题. 一.作业分析 1.第一次作业分析 1.1类图 1. ...

  5. python基础数据类型-练习

    1,有如下变量(tu是个元祖),请实现要求的功能 tu = ("alex", [11, 22, {"k1": 'v1', "k2": [&q ...

  6. powershell脚本:你的文件已经被黑客篡改.ps1

    本人原创powershell脚本分享. 脚本用途:列出某目录下,所有软件签名不符的文件. 系统需求: win7 + powershell 2.0 及 以上. #nd你的文件已经被黑客篡改.ps1 ps ...

  7. spring boot 全局配置属性一览

    # =================================================================== # COMMON SPRING BOOT PROPERTIE ...

  8. js之 单例模式

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  9. MIME 参考手册

    本文摘自http://www.w3school.com.cn/media/media_mimeref.asp MIME (Multipurpose Internet Mail Extensions) ...

  10. vue爬坑:把对象中的数据给了某个变量,改变一个对象的值,另一个对象也变化

    今天做项目碰到了 一个坑,一个vue变量赋值给一个新的变量,对这个新的变量里的值做更改,vue的变量也变了.记录一下这个坑坑~~ 然后百度搜到了一个解决方案: 就是把变量先转成字符串,再把字符串转成对 ...