網(wǎng)站建設(shè)和注冊北京seo包年
Swagger
Swagger簡介
Springboot整合swagger
Swagger 常用注解
一、Swagger簡介
? Swagger 是一系列 RESTful API 的工具,通過 Swagger 可以獲得項目的?種交互式文檔,客戶端 SDK 的自動生成等功能。
? Swagger 的目標(biāo)是為 REST APIs 定義一個標(biāo)準(zhǔn)的、與語?言無關(guān)的接口,使人和計算機(jī)在看不到源碼或者看不到文檔或者不能通過網(wǎng)絡(luò)流量檢測的情況下,能發(fā)現(xiàn)和理解各種服務(wù)的功能。當(dāng)服務(wù)通過 Swagger 定義,消費者就能與遠(yuǎn)程的服務(wù)互動通過少量的實現(xiàn)邏輯。Swagger(絲襪哥)是世界上最流行的 API 表達(dá)工具。
二、Springboot整合swagger
? 使用 Spring Boot 集成 Swagger 的理念是,使用用注解來標(biāo)記出需要在 API 文檔中展示的信息,Swagger 會根據(jù)項目中標(biāo)記的注解來生成對應(yīng)的 API 文檔。Swagger 被號稱世界上最流行的 API 工具,它提供了 API 管理的全套解決方案,API 文檔管理需要考慮的因素基本都包含,這里將講解最常用的定制內(nèi)容。
1、添加swagger坐標(biāo)
Spring Boot 集成 Swagger 3 很簡單,需要引入依賴并做基礎(chǔ)配置即可。
<dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>3.0.0</version>
</dependency>
2、Swagger Helloword 實現(xiàn)
2.1、創(chuàng)建springboot項目
在啟動類上加上@EnableOpenApi 注解 啟用swagger api文檔功能
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.oas.annotations.EnableOpenApi;@SpringBootApplication
@EnableOpenApi //啟動swagger api文檔注解
public class SpringBootWithSwaggerApplication {public static void main(String[] args) {SpringApplication.run(SpringBootWithSwaggerApplication.class, args);}}
2.2、寫一個接口
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;/*** @author 阿水* @create 2023-04-11 9:54*/
@RestController()
public class SwaggerController {@GetMapping ("hello")public String hello(String params) {return "hello swagger"+" param為:"+params;}
}
2.3、訪問地址
http://localhost:8080/swagger-ui/index.html
三、常用的配置注解
? Swagger 通過注解表明該接口會生成文檔,包括接口名、請求方法、參數(shù)、返回信息等
1、Api 注解和 ApiOperation 注解
-
@Api
使用在類上,表明是swagger資源,@API擁有兩個屬性:value、tags。
生成的api文檔會根據(jù)tags分類,直白的說就是這個controller中的所有接口生成的接口文檔都會在tags這個list下;tags如果有多個值,會生成多個list,每個list都顯示所有接口
value的作用類似tags,但是不能有多個值
語法:@Api(tags = "用戶操作")或@Api(tags = {"用戶操作","用戶操作2"})
-
@ApiOperation
使用于在方法上,表示一個http請求的操作
語法:@ApiOperation(value = "", notes = "", response = ) 屬性說明:value:方法說明標(biāo)題notes:方法詳細(xì)描述response:方法返回值類型
案例:使用@Api和@ApiOperation生成api文檔
import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;/*** @author 阿水* @create 2023-04-11 9:54*/ @RestController() @Api(tags = {"操作用戶"}) public class SwaggerController {@GetMapping ("hello")@ApiOperation(value = "swagger請求",notes = "阿水的第一個swagger請求",response = String.class)public String hello(String params) {return "hello swagger"+" param為:"+params;} }
2、ApiImplicitParams 注解和 ApiImplicitParam
@ApiImplicitParams 注解和 @ApiImplicitParam 用于對方法中的非對象參數(shù)(參數(shù)綁定到簡單類型時使用。)進(jìn)行說明
語法:
@ApiImplicitParams(value = {@ApiImplicitParam(name="", value = "", type = "", required = true, paramType = "", defaultValue = "")
})屬性說明:name:形參名稱value:形參的說明文字type:形參類型required:該參數(shù)是否必須 true|falseparamType: 用于描述參數(shù)是以何種方式傳遞到 Controller 的,它的值常見有: path, query, body 和 header path 表示參數(shù)是『嵌在』路徑中的,它和 @PathVariable 參數(shù)注解遙相呼應(yīng);query 表示參數(shù)是以 query string 的形式傳遞到后臺的(無論是 get 請求攜帶在 url 中,還是 post 請求攜帶在請求體中),它和 @RequestParam 參數(shù)注解遙相呼應(yīng);header 表示參數(shù)是『藏在』請求頭中傳遞到后臺的,它和 @RequestHeader 參數(shù)注解遙相呼應(yīng)的。form 不常用.defaultValue :參數(shù)默認(rèn)值
注意:@ApiImplicitParam 的 name 屬性要和 @RequestParam 或 @PathVariable 的 value 遙相呼應(yīng)。
案例:使用@ApiImplicitParams注解和 @ApiImplicitParam 對方法參數(shù)進(jìn)行說明
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;/*** @author 阿水* @create 2023-04-11 9:54*/
@RestController()
@Api(tags = {"操作用戶"})
public class SwaggerController {@GetMapping ("hello")@ApiOperation(value = "swagger請求",notes = "阿水的第一個swagger請求",response = String.class)@ApiImplicitParams(value ={@ApiImplicitParam(name="param1",value = "參數(shù)名1",type = "String",required = true,paramType = "query",defaultValue = "阿水所想的默認(rèn)值1" ),@ApiImplicitParam(name="param2",value = "參數(shù)名2",type = "String",required = true,paramType = "query",defaultValue = "阿水所想的默認(rèn)值2" )})public String hello(String param1,String param2) {return "hello swagger"+" param1為:"+param1+"param2為"+param2;}
}
3、ApiModel注解和 ApiModelProperty
-
@ApiModel
用在實體類上,表示對類進(jìn)行說明,用于實體類中的參數(shù)接收說明。
語法:@ApiModel("用戶類")public class Users {}
-
@ApiModelProperty
用于對實體類中的屬性進(jìn)行說明
@ApiModel("用戶類") @Data public class Users {@ApiModelProperty(value = "編碼:主鍵")private Integer id;@ApiModelProperty(value = "用戶名")private String username;@ApiModelProperty(value = "密碼")private String password;}
4、ApiResponse 和 ApiResponses
@ApiResponses 注解和 @ApiResponse 標(biāo)注在 Controller 的方法上,用來描述 HTTP 請求的響應(yīng)
/*** 添加用戶** @param user* @return*/@PostMapping("/add")@ApiOperation(value = "添加用戶",notes = "添加用戶信息",response = ResponseResult.class)@ApiResponses({ @ApiResponse(code = 200, message = "添加成功", response = ResponseResult.class),@ApiResponse(code = 500, message = "添加失敗", response = ResponseResult.class) })public ResponseResult<Void> addUser(@RequestBody User user) {//獲得生成的加密鹽user.setSalt(SaltUtils.getSalt());int n = userService.addUser(user);if (n > 0) {return new ResponseResult<Void>(200, "添加成功");}return new ResponseResult<Void>(500, "添加失敗");}
5、創(chuàng)建 SwaggerConfig 配置類
在 SwaggerConfig 中添加兩個方法:(其中一個方法是為另一個方法作輔助的準(zhǔn)備工作)
api()方法使用 @Bean,在啟動時初始化,返回實例 Docket(Swagger API 摘要對象),這里需要注意的是 .apis(RequestHandlerSelectors.basePackage("xxx.yyy.zzz"))
指定需要掃描的包路路徑,只有此路徑下的 Controller 類才會自動生成 Swagger API 文檔。
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;/*** Swagger配置類*/
@Configuration //項目啟動時加載此類
public class SwaggerConfig {@Beanpublic Docket api(){return new Docket(DocumentationType.OAS_30).apiInfo(apiInfo()).select()// 此處自行修改為自己的 Controller 包路徑。.apis(RequestHandlerSelectors.basePackage("com.lps.controller")).paths(PathSelectors.any()).build();}public ApiInfo apiInfo(){return new ApiInfoBuilder().title("阿水的項目接口文擋").description("阿水的 Project Swagger2 UserService Interface") //說明信息.termsOfServiceUrl("http://localhost:8080/swagger-ui/index.html") //文檔生成的主頁地址.version("1.0") //文檔版本.build();}
}
apiInfo()方法配置相對重要一些,主要配置頁面展示的基本信息包括,標(biāo)題、描述、版本、服務(wù)條款等,查看 ApiInfo 類的源碼還會發(fā)現(xiàn)支持 license 等更多的配置
四、springsecurity整合swagger
4.1,配置放行的地址
http.authorizeRequests().antMatchers( "/swagger-ui.html","/swagger-ui/*","/swagger-resources/**","/v2/api-docs","/v3/api-docs","/webjars/**").permitAll().anyRequest().authenticated();
4.2,替換UI
上面的整個過程已經(jīng)完成了,但是生成的接口文檔的頁面,其實很多人不太喜歡,覺得不太符合國人的使用習(xí)慣,所有又有一些大神,提供了其他的UI測試頁面。這個頁面的使用還是比較廣泛的。
導(dǎo)入以下依賴、重啟工程后訪問地址:http://localhost:8080/doc.html
<dependency><groupId>com.github.xiaoymin</groupId><artifactId>swagger-bootstrap-ui</artifactId><version>1.9.6</version></dependency>