项目开发常采用前后端分离的方式。前后端通过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. UVa LA 4636 Cubist Artwork 难度: 0

    题目 https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_pr ...

  2. 【Alpha】事后分析

    Alpha阶段终于告一段落,我们的团队也完整经历了从提出设想.用户需求分析,到开发.测试,再到部署上线.推广的流程."葫芦娃不想写代码"团队还是较出色地完成了Alpha阶段的工作, ...

  3. 构建Java开发环境(JDK)

    在我们学习Java前我们需要构建相对应的开发环境.JDK(Java Development Kit)是Java开发的必备条件. Java 的JDK是Sun公司的产品,但由于Sun公司被Oracle公司 ...

  4. Ubuntu17.04 安装搜狗中文输入法

    http://blog.csdn.net/ydyang1126/article/details/76223656

  5. net core 随笔

    UseApplicationInsights  这个有用到azure 才有用, 平时没用的话可以去掉. 遥测. 上下文指的是 进程间占有的资源空间. 当一个进程时间片到了或者资缺的时候就会让出CPU ...

  6. linux ubuntu 安装后没有root密码

    终端中输入:sudo passwd root 此时重新设置原登录用户的密码. 设置成功后在终端继续输入: su root 则出现#号,原用户名得到root权限.此时可以进行超级用户操作.

  7. angular 定时函数

    注入$interval,$timeout   服务 2.定义函数 var aa = $interval(function(){ $timout(function(){ ..... }) },,定时时间 ...

  8. 在当前TestSuite/TestCase run之前先run另一个TestSuite/TestCase

    在当前的TestSuite/TestCase的Setup Script里面写上这段代码: import com.eviware.soapui.model.support.PropertiesMap l ...

  9. Excel身份证验证,身份证校验公式

    =IF(LEN(Q4)=0,"空",IF(LEN(Q4)=15,"老号",IF(LEN(Q4)<>18,"位数不对",IF(CH ...

  10. Oracle数据库表的一些宏处理

    比如现在,有个数据库表,我想要知道这个数据库已经建了多少张表?每个表有多少条数据?每个表都有哪些字段?以及字段的说明? 下面就用SQL一一解决上面的问题: --所有已存在的表名和说明 select t ...