Spring Boot整合Swagger2的完整步驟詳解
前言
swagger,中文“拽”的意思。它是一個(gè)功能強(qiáng)大的api框架,它的集成非常簡單,不僅提供了在線文檔的查閱,
而且還提供了在線文檔的測試。另外swagger很容易構(gòu)建restful風(fēng)格的api。
一、Swagger概述
Swagger是一組圍繞OpenAPI規(guī)范構(gòu)建的開源工具,可幫助設(shè)計(jì)、構(gòu)建、記錄和使用REST API。
簡單說下,它的出現(xiàn)就是為了方便進(jìn)行測試后臺的restful形式的接口,實(shí)現(xiàn)動態(tài)的更新,當(dāng)我們在后臺的接口
修改了后,swagger可以實(shí)現(xiàn)自動的更新,而不需要認(rèn)為的維護(hù)這個(gè)接口進(jìn)行測試。
二、Swagger常用注解
swagger通過注解表明該接口會生成文檔,包括接口名、請求方法、參數(shù)、返回信息的等等。
- @Api:修飾整個(gè)類,描述Controller的作用
- @ApiOperation:描述一個(gè)類的一個(gè)方法,或者說一個(gè)接口
- @ApiParam:單個(gè)參數(shù)描述
- @ApiModel:用對象來接收參數(shù)
- @ApiProperty:用對象接收參數(shù)時(shí),描述對象的一個(gè)字段
- @ApiResponse:HTTP響應(yīng)其中1個(gè)描述
- @ApiResponses:HTTP響應(yīng)整體描述
- @ApiIgnore:使用該注解忽略這個(gè)API
- @ApiError :發(fā)生錯(cuò)誤返回的信息
- @ApiParamImplicitL:一個(gè)請求參數(shù)
- @ApiParamsImplicit 多個(gè)請求參數(shù)
三、SpringBoot整合Swagger
3.1 添加依賴
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>
3.2 添加SwaggerConfiguration
通過@Configuration注解,表明它是一個(gè)配置類,@EnableSwagger2開啟swagger2。
apiINfo()配置一些基本的信息。apis()指定掃描的包會生成文檔。
再通過createRestApi函數(shù)創(chuàng)建Docket的Bean之后,apiInfo()用來創(chuàng)建該Api的基本信息(這些基本信息會
展現(xiàn)在文檔頁面中)。select()函數(shù)返回一個(gè)ApiSelectorBuilder實(shí)例用來控制哪些接口暴露給Swagger來
展現(xiàn),本例采用指定掃描的包路徑來定義,Swagger會掃描該包下所有Controller定義的API,并產(chǎn)生文檔內(nèi)容
(除了被@ApiIgnore指定的請求)。
package com.lance.learn.springbootswagger.configuration;
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;
/**
* @author lance(ZYH)
* @function Swagger啟動配置類
* @date 2018-07-09 21:24
*/
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
/**
* swagger2的配置文件,這里可以配置swagger2的一些基本的內(nèi)容,比如掃描的包等等
* @return
*/
@Bean
public Docket createRestfulApi(){
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/")
.select()
.apis(RequestHandlerSelectors.basePackage("com.lance.learn.springbootswagger.controller")) //暴露接口地址的包路徑
.paths(PathSelectors.any())
.build();
}
/**
* 構(gòu)建 api文檔的詳細(xì)信息函數(shù),注意這里的注解引用的是哪個(gè)
* @return
*/
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
//頁面標(biāo)題
.title("Spring Boot 測試使用 Swagger2 構(gòu)建RESTful API")
//創(chuàng)建人
.contact(new Contact("LanveToBigData", "http://www.cnblogs.com/zhangyinhua/", "917484312@qq.com"))
//版本號
.version("1.0")
//描述
.description("API 描述")
.build();
}
}
3.3 Controller文檔內(nèi)容
描述主要來源于函數(shù)等命名產(chǎn)生,對用戶并不友好,我們通常需要自己增加一些說明來豐富文檔內(nèi)容。
如下所示,我們通過@ApiOperation注解來給API增加說明、通過@ApiImplicitParams、@ApiImplicitParam
注解來給參數(shù)增加說明。
1)實(shí)例一
package com.lance.learn.springbootswagger.controller;
import com.lance.learn.springbootswagger.bean.Book;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import java.util.*;
/**
* @author lance(ZYH)
* @function
* @date 2018-07-09 21:39
*/
@RestController
@RequestMapping(value = "/bookcurd")
public class BookController {
Map<Long, Book> books = Collections.synchronizedMap(new HashMap<Long, Book>());
@ApiOperation(value="獲取圖書列表", notes="獲取圖書列表")
@RequestMapping(value={""}, method= RequestMethod.GET)
public List<Book> getBook() {
List<Book> book = new ArrayList<>(books.values());
return book;
}
@ApiOperation(value="創(chuàng)建圖書", notes="創(chuàng)建圖書")
@ApiImplicitParam(name = "book", value = "圖書詳細(xì)實(shí)體", required = true, dataType = "Book")
@RequestMapping(value="", method=RequestMethod.POST)
public String postBook(@RequestBody Book book) {
books.put(book.getId(), book);
return "success";
}
@ApiOperation(value="獲圖書細(xì)信息", notes="根據(jù)url的id來獲取詳細(xì)信息")
@ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long",paramType = "path")
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public Book getBook(@PathVariable Long id) {
return books.get(id);
}
@ApiOperation(value="更新信息", notes="根據(jù)url的id來指定更新圖書信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "圖書ID", required = true, dataType = "Long",paramType = "path"),
@ApiImplicitParam(name = "book", value = "圖書實(shí)體book", required = true, dataType = "Book")
})
@RequestMapping(value="/{id}", method= RequestMethod.PUT)
public String putUser(@PathVariable Long id, @RequestBody Book book) {
Book book1 = books.get(id);
book1.setName(book.getName());
book1.setPrice(book.getPrice());
books.put(id, book1);
return "success";
}
@ApiOperation(value="刪除圖書", notes="根據(jù)url的id來指定刪除圖書")
@ApiImplicitParam(name = "id", value = "圖書ID", required = true, dataType = "Long",paramType = "path")
@RequestMapping(value="/{id}", method=RequestMethod.DELETE)
public String deleteUser(@PathVariable Long id) {
books.remove(id);
return "success";
}
@ApiIgnore//使用該注解忽略這個(gè)API
@RequestMapping(value = "/hi", method = RequestMethod.GET)
public String jsonTest() {
return " hi you!";
}
}
2)實(shí)例二
package com.lance.learn.springbootswagger.controller;
import com.lance.learn.springbootswagger.bean.User;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import java.util.*;
/**
* @author lance(ZYH)
* @function
* @date 2018-07-09 22:00
*/
@RestController
@RequestMapping(value="/users")
public class UserDetailController {
static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());
@ApiOperation(value="獲取用戶列表", notes="")
@RequestMapping(value={""}, method= RequestMethod.GET)
public List<User> getUserList() {
List<User> r = new ArrayList<User>(users.values());
return r;
}
@ApiOperation(value="創(chuàng)建用戶", notes="根據(jù)User對象創(chuàng)建用戶")
@ApiImplicitParam(name = "user", value = "用戶詳細(xì)實(shí)體user", required = true, dataType = "User")
@RequestMapping(value="", method=RequestMethod.POST)
public String postUser(@RequestBody User user) {
users.put(user.getId(), user);
return "success";
}
@ApiOperation(value="獲取用戶詳細(xì)信息", notes="根據(jù)url的id來獲取用戶詳細(xì)信息")
@ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long")
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public User getUser(@PathVariable Long id) {
return users.get(id);
}
@ApiOperation(value="更新用戶詳細(xì)信息", notes="根據(jù)url的id來指定更新對象,并根據(jù)傳過來的user信息來更新用戶詳細(xì)信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long"),
@ApiImplicitParam(name = "user", value = "用戶詳細(xì)實(shí)體user", required = true, dataType = "User")
})
@RequestMapping(value="/{id}", method=RequestMethod.PUT)
public String putUser(@PathVariable Long id, @RequestBody User user) {
User u = new User();
users.put(id, u);
return "success";
}
@ApiOperation(value="刪除用戶", notes="根據(jù)url的id來指定刪除對象")
@ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long")
@RequestMapping(value="/{id}", method=RequestMethod.DELETE)
public String deleteUser(@PathVariable Long id) {
users.remove(id);
return "success";
}
}
3.4 web界面查看

四、項(xiàng)目代碼地址
https://github.com/LanceToBigData/SpringBootLearning/tree/develop/SpringBoot-Swagger
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
JavaAgent實(shí)現(xiàn)http接口發(fā)布方式淺析
這篇文章主要介紹了JavaAgent實(shí)現(xiàn)http接口發(fā)布方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-03-03
java的arraylist排序示例(arraylist用法)
這篇文章主要介紹了java的arraylist排序示例,學(xué)習(xí)一下arraylist的用法,需要的朋友可以參考下2014-03-03
java中Class.getMethods()和Class.getDeclaredMethods()方法的區(qū)別
這篇文章主要介紹了java中Class.getMethods()和Class.getDeclaredMethods()方法的區(qū)別 ,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-09-09
Spring Boot 整合 ShedLock 處理定時(shí)任務(wù)重復(fù)執(zhí)行的問題小結(jié)
ShedLock是解決分布式系統(tǒng)中定時(shí)任務(wù)重復(fù)執(zhí)行問題的Java庫,通過在數(shù)據(jù)庫中加鎖,確保只有一個(gè)節(jié)點(diǎn)在指定時(shí)間執(zhí)行任務(wù),它與SpringScheduler、Quartz等框架結(jié)合使用,本文介紹Spring Boot 整合 ShedLock 處理定時(shí)任務(wù)重復(fù)執(zhí)行的問題,感興趣的朋友一起看看吧2025-02-02
Spring?invokeBeanFactoryPostProcessors方法刨析源碼
invokeBeanFactoryPostProcessors該方法會實(shí)例化所有BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor的實(shí)例并且執(zhí)行postProcessBeanFactory與postProcessBeanDefinitionRegistry方法2023-01-01

