springboot+mybatis-puls利用swagger構建api文檔


項目開發常采用前后端分離的方式。前后端通過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即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM