SpringBoot整合Swagger2API文檔詳細使用
- 引言
- 構建MAVEN工程
- 整合Mybatis提供一個接口供於測試
- 引入mybatis依賴
- 數據庫SQL
- 配置YML文件
- pojo類
- mapper層
- service層
- controller層(根據Id查詢User信息)
- 啓動類加上掃mapper包的註解
- 啓動項目地址欄輸入[http://localhost:8080/getById?id=1](http://localhost:8080/getById?id=1)
- 運行[http://localhost:8080/swagger-ui.html](http://localhost:8080/swagger-ui.html)看有沒有接口生產
- 改造controller層
- 再次輸入[http://localhost:8080/swagger-ui.html](http://localhost:8080/swagger-ui.html)
- 最終工程結構展示
- swagger的一些註解及參數說明
引言
本教程採用eclipse純手動構建,望知悉。
swagger也稱爲Open API,Swagger從API文檔中手動完成工作,並提供一系列用於生成,可視化和維護API文檔的解決方案。簡單的說就是一款讓你更好的書寫API文檔的框架。我們爲什麼選擇swagger,現在的網站開發結果越來越注重前後端的分離,比如以前的webFrom到現在的mvc模式都是爲了這個前後端的分離。就算再如何的分離實現,也是不可避免的要進行數據交互的,那麼接口的重要性就提現出來了。他成了前端和後端交互的重要途徑,API文檔也因此成了前端開發人員與後端開發人員的重要紐帶。所有我們有一個API文檔框架豈不是美哉。
構建MAVEN工程
創建maven project
引入pom依賴
<!-- SpringBoot2.0依賴 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<dependencies>
<!--SpringBoot WEB組件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
</dependencies>
創建swagger配置類
package com.xqm.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration // spring boot配置註解
@EnableSwagger2 // 啓用swagger2功能註解
public class Swagger2Config {
@Bean
public Docket createRestfulApi() {// api文檔實例
return new Docket(DocumentationType.SWAGGER_2)// 文檔類型:DocumentationType.SWAGGER_2
.apiInfo(apiInfo())// api信息
.select()// 構建api選擇器
.apis(RequestHandlerSelectors.basePackage("com.xqm.controller"))// api選擇器選擇api的包(提供接口的包)
.paths(PathSelectors.any())// api選擇器選擇包路徑下任何api顯示在文檔中
.build();// 創建文檔
}
// 構建 api文檔的詳細信息函數,注意這裏的註解引用的是哪個
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 頁面標題
.title("測試swagger")
// 創建人
.contact(new Contact("MarryFeng", "http://localhost:8080", ""))
// 版本號
.version("1.0")
// 描述
.description("API 描述").build();
}
/*
* private ApiInfo apiInfo() {//接口的相關信息 return new ApiInfoBuilder()
* .title("Spring Boot中使用Swagger2構建RESTful接口") .description("接口描述")
* .termsOfServiceUrl("termsOfServiceUrl") .contact("new Contact")
* .version("1.0")
* .license("http://springfox.github.io/springfox/docs/current/")
* .licenseUrl("http://springfox.github.io/springfox/docs/current/") .build(); }
*/
}
創建springboot啓動類
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) throws Exception {
SpringApplication.run(App.class, args);
}
}
啓動工程,瀏覽器輸入http://localhost:8080/swagger-ui.html
- 看到以下界面就說明構建成功了
整合Mybatis提供一個接口供於測試
引入mybatis依賴
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!-- mysql 依賴 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
數據庫SQL
CREATE TABLE `user` (
`id` int(6) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_520_ci DEFAULT NULL,
`age` int(6) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_520_ci
配置YML文件
server:
port: 8080
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf8
username: root
password: root
logging:
level:
mapper: debug
pojo類
package com.xqm.pojo;
public class User {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
mapper層
package com.xqm.mapper;
import org.apache.ibatis.annotations.Select;
import com.xqm.pojo.User;
public interface UserMapper {
@Select("select * from user where id = #{id}")
public User getById(Integer id);
}
service層
package com.xqm.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xqm.mapper.UserMapper;
import com.xqm.pojo.User;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getById(Integer id) {
return userMapper.getById(id);
}
}
controller層(根據Id查詢User信息)
package com.xqm.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.xqm.pojo.User;
import com.xqm.service.UserService;
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("getById")
public User getById(Integer id) {
return userService.getById(id);
}
}
啓動類加上掃mapper包的註解
package com;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.xqm.mapper")//掃描mapper包
public class App {
public static void main(String[] args) throws Exception {
SpringApplication.run(App.class, args);
}
}
啓動項目地址欄輸入http://localhost:8080/getById?id=1
- 看到查詢出數據說明接口寫的沒有問題
運行http://localhost:8080/swagger-ui.html看有沒有接口生產
- 很顯然沒有看到接口生產
改造controller層
package com.xqm.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.xqm.pojo.User;
import com.xqm.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
@RestController
@Api(value = "用戶接口", tags = { "userAPi" })
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("getById/{id}")
@ApiOperation(value = "根據userId查詢用戶信息", notes = "查詢數據庫中用戶信息")
@ApiImplicitParam(name="id",value="userId",paramType = "path",required=true,dataType = "Integer")
public User getById(@PathVariable Integer id) {
return userService.getById(id);
}
}
再次輸入http://localhost:8080/swagger-ui.html
- 點開後發現有多個請求,但請求方式不同,那是因爲我們接口上使用的是@RequestMapping這個註解,一般在實際開發中我們都要指定請求方式,我們把它改成@GetMapping再看
最終工程結構展示
swagger的一些註解及參數說明
@Api:用在請求的類上,表示對類的說明
tags=“說明該類的作用,可以在UI界面上看到的註解”
value=“該參數沒什麼意義,在UI界面上也看到,所以不需要配置”
@ApiOperation:用在請求的方法上,說明方法的用途、作用
value=“說明方法的用途、作用”
notes=“方法的備註說明”
@ApiImplicitParams:用在請求的方法上,表示一組參數說明
@ApiImplicitParam:用在@ApiImplicitParams註解中,指定一個請求參數的各個方面
name:參數名
value:參數的漢字說明、解釋
required:參數是否必須傳
paramType:參數放在哪個地方
header --> 請求參數的獲取:@RequestHeader
query --> 請求參數的獲取:@RequestParam
path(用於restful接口)–> 請求參數的獲取:@PathVariable
body(不常用)
form(不常用)
dataType:參數類型,默認String,其它值dataType=“Integer”
defaultValue:參數的默認值
@ApiResponses:用在請求的方法上,表示一組響應
@ApiResponse:用在@ApiResponses中,一般用於表達一個錯誤的響應信息
code:數字,例如400
message:信息,例如"請求參數沒填好"
response:拋出異常的類
@ApiModel:用於響應類上,表示一個返回響應數據的信息
(這種一般用在post創建的時候,使用@RequestBody這樣的場景,請求參數無法使用@ApiImplicitParam註解進行描述的時候)
@ApiModelProperty:用在屬性上,描述響應類的屬性
下期再見。。。