spring boot整合Swagger2的示例代碼
Swagger 是一個(gè)規(guī)范和完整的框架,用于生成、描述、調(diào)用和可視化RESTful風(fēng)格的 Web 服務(wù)。總體目標(biāo)是使客戶端和文件系統(tǒng)作為服務(wù)器以同樣的速度來(lái)更新。文件的方法,參數(shù)和模型緊密集成到服務(wù)器端的代碼,允許API來(lái)始終保持同步。Swagger 讓部署管理和使用功能強(qiáng)大的API從未如此簡(jiǎn)單。
1.代碼示例
1).在pom.xml文件中引入Swagger2
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.6.1</version> </dependency>
2).在Application同級(jí)目錄下添加Swagger2的配置類
package com.example;
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2構(gòu)建RESTful APIs")
.description("spring boot整合swagger2")
.termsOfServiceUrl("www.baidu.com")
.contact("牛頭人")
.version("1.0")
.build();
}
}如上代碼所示,通過(guò) @Configuration 注解,讓Spring來(lái)加載該類配置。再通過(guò) @EnableSwagger2 注解來(lái)啟用Swagger2。
通過(guò) createRestApi 函數(shù)創(chuàng)建 Docket 的Bean之后, apiInfo() 用來(lái)創(chuàng)建該Api的基本信息(這些基本信息會(huì)展現(xiàn)在文檔頁(yè)面中)。 select() 函數(shù)返回一個(gè) ApiSelectorBuilder 實(shí)例用來(lái)控制哪些接口給Swagger來(lái)展現(xiàn),本例采用指定掃描的包路徑來(lái)定義,Swagger會(huì)掃描該包下所有Controller定義的API,并產(chǎn)生文檔內(nèi)容(除了被 @ApiIgnore 指定的請(qǐng)求)。
3).新建User實(shí)體類
package com.example.swagger2;
public class User {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}4).新建SwaggerDemoController類
package com.example.swagger2;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
@RestController
@RequestMapping(value="/api")
@Api("SwaggerDemoController相關(guān)api")
public class SwaggerDemoController {
static Map<String, User> users = Collections.synchronizedMap(new HashMap<String, User>());
@ApiOperation(value="獲取用戶列表", notes="")
@ApiResponses({
@ApiResponse(code=400,message="請(qǐng)求參數(shù)沒(méi)填好"),
@ApiResponse(code=404,message="請(qǐng)求路徑?jīng)]有或頁(yè)面跳轉(zhuǎn)路徑不對(duì)")
})
@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對(duì)象創(chuàng)建用戶")
@ApiImplicitParam(name = "user", value = "用戶詳細(xì)實(shí)體user", required = true, dataType = "User")
@ApiResponses({
@ApiResponse(code=400,message="請(qǐng)求參數(shù)沒(méi)填好"),
@ApiResponse(code=404,message="請(qǐng)求路徑?jīng)]有或頁(yè)面跳轉(zhuǎn)路徑不對(duì)")
})
@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來(lái)獲取用戶詳細(xì)信息")
@ApiImplicitParam(name = "id", value = "用戶ID",paramType="path", required = true, dataType = "String")
@ApiResponses({
@ApiResponse(code=400,message="請(qǐng)求參數(shù)沒(méi)填好"),
@ApiResponse(code=404,message="請(qǐng)求路徑?jīng)]有或頁(yè)面跳轉(zhuǎn)路徑不對(duì)")
})
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public User getUser(@PathVariable String id) {
System.out.println("id="+id);
return users.get(id);
}
@ApiOperation(value="更新用戶詳細(xì)信息", notes="根據(jù)url的id來(lái)指定更新對(duì)象,并根據(jù)傳過(guò)來(lái)的user信息來(lái)更新用戶詳細(xì)信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用戶ID",paramType="path", required = true, dataType = "String"),
@ApiImplicitParam(name = "user", value = "用戶詳細(xì)實(shí)體user", required = true, dataType = "User")
})
@ApiResponses({
@ApiResponse(code=400,message="請(qǐng)求參數(shù)沒(méi)填好"),
@ApiResponse(code=404,message="請(qǐng)求路徑?jīng)]有或頁(yè)面跳轉(zhuǎn)路徑不對(duì)")
})
@RequestMapping(value="/{id}", method=RequestMethod.PUT)
public String putUser(@PathVariable String id, @RequestBody User user) {
System.out.println("id="+id);
User u = users.get(id);
u.setName(user.getName());
users.put(id, u);
return "success";
}
@ApiOperation(value="刪除用戶", notes="根據(jù)url的id來(lái)指定刪除對(duì)象")
@ApiImplicitParam(name = "id", value = "用戶ID",paramType="path", required = true, dataType = "String")
@ApiResponses({
@ApiResponse(code=400,message="請(qǐng)求參數(shù)沒(méi)填好"),
@ApiResponse(code=404,message="請(qǐng)求路徑?jīng)]有或頁(yè)面跳轉(zhuǎn)路徑不對(duì)")
})
@RequestMapping(value="/{id}", method=RequestMethod.DELETE)
public String deleteUser(@PathVariable String id) {
System.out.println("id="+id);
users.remove(id);
return "success";
}
}說(shuō)明:
@Api:用在類上,說(shuō)明該類的作用
@ApiOperation:用在方法上,說(shuō)明方法的作用
@ApiImplicitParams:用在方法上包含一組參數(shù)說(shuō)明
@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一個(gè)請(qǐng)求參數(shù)的各個(gè)方面
paramType:參數(shù)放在哪個(gè)地方
header-->請(qǐng)求參數(shù)的獲?。篅RequestHeader
query-->請(qǐng)求參數(shù)的獲?。篅RequestParam
path(用于restful接口)-->請(qǐng)求參數(shù)的獲?。篅PathVariable
body(不常用)
form(不常用)
name:參數(shù)名
dataType:參數(shù)類型
required:參數(shù)是否必須傳
value:參數(shù)的意思
defaultValue:參數(shù)的默認(rèn)值
@ApiResponses:用于表示一組響應(yīng)
@ApiResponse:用在@ApiResponses中,一般用于表達(dá)一個(gè)錯(cuò)誤的響應(yīng)信息
code:數(shù)字,例如400
message:信息,例如"請(qǐng)求參數(shù)沒(méi)填好"
response:拋出異常的類
@ApiModel:描述一個(gè)Model的信息(這種一般用在post創(chuàng)建的時(shí)候,使用@RequestBody這樣的場(chǎng)景,請(qǐng)求參數(shù)無(wú)法使用@ApiImplicitParam注解進(jìn)行描述的時(shí)候)
@ApiModelProperty:描述一個(gè)model的屬性
通過(guò) @ApiOperation 注解來(lái)給API增加說(shuō)明、通過(guò) @ApiImplicitParams 、 @ApiImplicitParam 注解來(lái)給參數(shù)增加說(shuō)明。
需要注意的是:

如果ApiImplicitParam中的phone的paramType是query的話,是無(wú)法注入到rest路徑中的,而且如果是path的話,是不需要配置ApiImplicitParam的,即使配置了,其中的value="用戶ID"也不會(huì)在swagger-ui展示出來(lái)。
具體其他的注解,查看:
https://github.com/swagger-api/swagger-core/wiki/Annotations#apimodel
2.測(cè)試:
啟動(dòng)服務(wù),瀏覽器輸入"http://localhost:8080/swagger-ui.html"

GET紅框:method=RequestMethod.GET
右邊紅框:@ApiOperation
parameter紅框:@ApiImplicitParams系列注解
response messages紅框:@ApiResponses系列注解
輸入?yún)?shù)后,點(diǎn)擊"try it out!",查看響應(yīng)內(nèi)容:

以上所述是小編給大家介紹的spring boot整合Swagger2的示例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
利用HttpUrlConnection 上傳 接收文件的實(shí)現(xiàn)方法
下面小編就為大家?guī)?lái)一篇利用HttpUrlConnection 上傳 接收文件的實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-11-11
java使用分隔符連接數(shù)組中每個(gè)元素的實(shí)例
今天小編就為大家分享一篇java使用分隔符連接數(shù)組中每個(gè)元素的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
Java向上轉(zhuǎn)型和向下轉(zhuǎn)型的區(qū)別說(shuō)明
這篇文章主要介紹了Java向上轉(zhuǎn)型和向下轉(zhuǎn)型的區(qū)別說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
使用MyBatis攔截器實(shí)現(xiàn)sql查詢權(quán)限動(dòng)態(tài)修改代碼實(shí)例
這篇文章主要介紹了使用MyBatis攔截器實(shí)現(xiàn)sql查詢權(quán)限動(dòng)態(tài)修改代碼實(shí)例,為了不耦合,現(xiàn)在的方案是在需要鑒權(quán)的Mybatis?Mapper方法上增加一個(gè)注解,在運(yùn)行過(guò)程中判斷該注解存在即對(duì)sql進(jìn)行修改,需要的朋友可以參考下2023-08-08
spring boot tomcat版本升級(jí)的實(shí)現(xiàn)示例
本文主要介紹了spring boot tomcat版本升級(jí)的實(shí)現(xiàn)示例,將tomcat升級(jí)一個(gè)小版本升級(jí)到9.0.44版本,文中通過(guò)圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-11-11
SpringBoot整合redis+Aop防止重復(fù)提交的實(shí)現(xiàn)
Spring Boot通過(guò)AOP可以實(shí)現(xiàn)防止表單重復(fù)提交,本文主要介紹了SpringBoot整合redis+Aop防止重復(fù)提交的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
SpringBoot數(shù)據(jù)脫敏的實(shí)現(xiàn)示例
數(shù)據(jù)脫敏主要應(yīng)用在客戶安全數(shù)據(jù)或商業(yè)性敏感數(shù)據(jù)的情況,本文主要介紹了SpringBoot數(shù)據(jù)脫敏的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-05-05
java8 toMap問(wèn)題(key重復(fù)如何解決)
這篇文章主要介紹了java8 toMap問(wèn)題(key重復(fù)如何解決),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
Springboot之自定義全局異常處理的實(shí)現(xiàn)
這篇文章主要介紹了Springboot之自定義全局異常處理的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08

