项目开发常采用前后端分离的方式。前后端通过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++重要知识点

    C++重要知识点精华总结 cin的使用: 1>cin>>a;键盘读入数据赋值给a; 1>程序的输入都建有一个缓冲区,即输入缓冲区.一次输入过程是这样的,当一次键盘输入结束时会将 ...

  2. __name__ __doc__ __package__

    __name__只有主程序调用才可以 如果自己的唯一入口被调用 if __name__ == '__main__' : 才执行下面的代码 """ 这个是format的注释 ...

  3. java----判断闰年和平年

    public class year{ public static void main(String[] args){ int year=2010; if((year%4==0&&yea ...

  4. nodejs操作 mongoose(mongodb)和Sequelize(mysql)查询数据后添加新属性未生效

    最近在着手koa时候,发现mongoose(mongodb)查询数据库后添加新属性,前端拿不到新属性问题, 然后测试了一下Sequelize(mysql),发现也有同样的问题存在.此时着手干! 1.1 ...

  5. CSS可见区域全局居中

    top:$(document).scrollTop() + ($(document).height() - $(document).scrollTop())/2,

  6. PHP取凌晨时间戳

    百度出来的没一个正确答案 在此纠正 strtotime('today midnight'); // 今天凌晨时间戳 strtotime('+1 day midnight'); // 明天凌晨时间戳

  7. sql表中数据遍历

    步骤: 1:先定义一个临时表,把需要用的数据放入临时表中,如果数据不连续,则在临时表中定义一个自增长键 DECLARE @temp table(Id INT IDENTITY(1, 1) ,ShopC ...

  8. Unity 关于AssetBundle读取场景

    一. 1.关于如何打包成ab包,就不多说了,网上很多教程,siki学院也有siki老师的免费视频教程挺详细的,可以看看 http://www.sikiedu.com/my/course/74 2.为了 ...

  9. 浅析Hashmap和Hashtable

    一.Hashmap不是线程安全的,而Hashtable是线程安全的 通过查看源码可以发现,hashmap类中的方法无synchronized关键字,而hashtable类中的方法有synchroniz ...

  10. 阻塞队列 - java基于链表的简单实现

    1.阻塞队列的原理 阻塞队列与普通队列的区别在于:阻塞队列为空时,从队列中获取元素的操作将会被阻塞,当队列为满时,往队列里添加元素的操作会被阻塞. 试图从空的阻塞队列中获取元素的线程将会被阻塞,直到其 ...