1. 程式人生 > >Spring Boot整合Swagger2

Spring Boot整合Swagger2

Spring Boot整合Swagger2

Swagger 介紹

Swagger2是一款RESTFUL介面的文件線上自動生成和功能測試功能軟體
Swagger 是一個規範和完整的框架,用於生成、描述、呼叫和視覺化 RESTful 風格的 Web 服務。總體目標是使客戶端和檔案系統作為伺服器以同樣的速度來更新。檔案的方法,引數和模型緊密整合到伺服器端的程式碼,允許API來始終保持同步。Swagger 讓部署管理和使用功能強大的API從未如此簡單

新增入Swagger2的依賴

<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.8.0</version>
</dependency>
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</
artifactId
>
<version>2.8.0</version> </dependency>

configuration

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("demo")
                .apiInfo
(getApiInfo()) .select() //設定basePackage會將包下的所有被@Api標記類的所有方法作為api .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) //只有標記了@ApiOperation的方法才會暴露出給swagger .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .paths(PathSelectors.regex("/api/.*")).build(); } private ApiInfo getApiInfo(){ return new ApiInfoBuilder() .title("API介面文件") .description("swagger2 demo api") .termsOfServiceUrl("http://localhost/swagger-ui.html") .version("1.0") .contact(new Contact("Kiana", "http://localhost/swagger-ui.html", "[email protected]")) .build(); } }

apis(RequestHandlerSelectors.basePackage(“com.example.demo.controller”))

會將包下的所有被@Api標記的類帶有@RequestMapping或者XxxMapping都會給暴露給swagger

apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))

只有在類上使用@Api註解標註並且在方法上使用@ApiOperation註解才會暴露給swagger,這種方式沒有包名的限制,可以將需要暴露的介面分散到各個包裡,只要類上有@Api註解方法上有@ApiOperation註解就能暴露出來,如果不想暴露出來就不用使用這兩個註解

Swagger 各註解說明

@RequestMapping("/api/v1.0/video")
@RestController
@Api(value = "video API", tags = "video", description = "視訊相關介面")
public class VideoController

@Api用來標識Class

@ApiOperation(value = "獲取視訊流", notes = "獲取視訊流資訊")
@ApiResponses({
    @ApiResponse(code = 200, message = "success"),
    @ApiResponse(code = 10001, message = "secret_key與token不符合"),
    @ApiResponse(code = 10002, message = "視訊流型別錯誤", response = Exception.class)
})
@PostMapping("/getVideo")
public String getVideo(@ApiParam(name = "secret_key", value = "祕鑰", required = true) @RequestParam String secret_key,
                       @ApiParam(name = "token", value = "token", required = true) @RequestParam String token,
                       @ApiParam(name = "type", value = "流型別", required = true) @RequestParam String type){
    return "{'type': " + type + ", 'url': 'rtmp://localhost/video', 'urlHD': 'rtmp://localhost/hd/video'}";
}

@ApiOperation(value = “介面方法的名稱”, notes = “備註說明”)
@ApiParam(name = “引數名稱”, value = “備註說明”, required = 是否必須):標註在方法的引數上 用於描述引數的名稱、備註、是否必須等資訊
@ApiImplicitParams: 用於包含多個@ApiImplicitParam
@ApiResponse(code = 0, message = “success”),

  • code:響應碼,例如400
  • message:資訊,一般是對code的描述
  • response:丟擲異常的類
@ApiOperation(value = "修改視訊流", notes = "修改視訊流資訊")
@ApiImplicitParams({
    @ApiImplicitParam(dataTypeClass = String.class, paramType = "header", name = "id", value = "id標識", required = true),
    @ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "url", value = "高清視訊流", required = true),
    @ApiImplicitParam(dataTypeClass = String.class, paramType = "path", name = "type", value = "視訊流型別", required = true),
    @ApiImplicitParam(dataTypeClass = String.class, paramType = "body", name = "hdurl", value = "超清視訊流", required = true)
})
@PutMapping("/update")
public String updateVideo(@RequestHeader String id, @RequestParam String url, @PathVariable String type, @RequestBody String hdurl){
    return "{'id': " + id + ", 'url':" + url + ", 'type':" + type + ", 'hdurl':" + hdurl +"}";
}

@ApiImplicitParam用於描述方法的引數,標註在方法上,和@ApiParam功能一樣,只是標註的位置不同而已

  • paramType:引數型別,即引數放在哪個地方
    • header–>請求引數的獲取:@RequestHeader,引數放在請求頭
    • query–>請求引數的獲取:@RequestParam,引數追加在url後面
    • path(用於restful介面)–>請求引數的獲取:@PathVariable
    • body 使用@RequestBody接收資料 POST有效,引數放在請求體中
  • name:引數名
  • dataType:引數的資料型別
  • required:引數是否必須傳
  • value:引數的描述
  • defaultValue:引數的預設值
    @ApiImplicitParams: 用於包含多個@ApiImplicitParam
    @ApiModelProperty(value = "當前頁", required = true)
    private Integer page;

    @ApiModelProperty(value = "每頁記錄數", required = true)
    private Integer pageSize;

@ApiModel:描述一個Model的資訊(這種一般用在post建立的時候,使用@RequestBody這樣的場景,請求引數無法使用@ApiImplicitParam註解進行描述的時候)
@ApiModelProperty:描述一個model的屬性

  • value 引數名稱
  • required 是否必須 boolean
  • hidden 是否隱藏 boolean

@ApiIgnore:用於或略該介面,不生成該介面的文件


測試

啟動專案後訪問http://localhost/swagger-ui.html
在這裡插入圖片描述
注意:swagger可能不相容IE和FireFox,可以使用Chrome訪問


swagger 聚合多個專案

當有多個專案介面需要生產介面文件時,swagger可以做到將多個專案合併到一個swagger上,這樣便於介面的使用,高版本的可以通過SwaggerResourcesProvider介面來實現

@Component
@Primary
public class DocumentationConfiguration implements SwaggerResourcesProvider {
    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> list = new ArrayList<>();
        list.add(getSwaggerResource("視訊API-V1.0", "/v2/api-docs?group=demo", "2.0"));
        list.add(getSwaggerResource("視訊API-V2.0", "/v2/api-docs?group=demo", "2.0"));
        return list;
    }

    private SwaggerResource getSwaggerResource(String name, String url, String version){
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setUrl(url);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }
}

實現SwaggerResourcesProvider介面中的get()方法即可完成,
name: 頁面上select的option
url: 其他專案swagger的docs的url
在這裡插入圖片描述

version: docs檔案中的swagger屬性,預設2.0

整合多個專案swagger的效果:
在這裡插入圖片描述
選擇選項卡就能訪問不同的api


跨域問題

通常情況下不同的專案部署在不同的伺服器上,這樣訪問綜合的swagger時就造成了跨域訪問的問題,
要解決這種跨域,則配置CORS,設定允許跨域請求的地址、請求頭、請求到的方法等配置

全域性配置

@Configuration 
public class CORSConfiguration { 
	@Bean 
	public CorsFilter corsFilter() { 
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 
		CorsConfiguration corsConfiguration = new CorsConfiguration(); 
		// 1 設定訪問源地址 
		corsConfiguration.addAllowedOrigin("*"); 
		// 2 設定訪問源請求頭 
		corsConfiguration.addAllowedHeader("*"); 
		// 3 設定訪問源請求方法 
		corsConfiguration.addAllowedMethod("*"); 
		// 4 對介面配置跨域設定 
		source.registerCorsConfiguration("/**", corsConfiguration); 
		return new CorsFilter(source); 
	} 
}
@Configuration 
public class WebMvcConfiguration implements WebMvcConfigurer { 
	@Override 
	public void addCorsMappings(CorsRegistry registry) { 
	registry.addMapping("/**") 
	.allowedOrigins("*") 
	.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH") 
	.allowCredentials(true) 
	.maxAge(3600); 
	} 
}

單個配置

如果只需要將一個類中的相關介面進行跨域,可以使用@CrossOrigin註解,標記在class上


轉載
Spring Boot入門教程(七): Swagger2