Spring Cloud微服務項目搭建系列文章(七):API處理之Swagger集成

上一篇異常處理我們講解了關於異常的處理,本文主要介紹對於API的處理。

本文項目地址:

源碼地址

現在Spring對於web的處理分成2中方式:

一種是傳統的webmvc的方式,基於http的

一種是基於reactor和netty實現的,webflux的方式。

因此Swagger也提供了2種集成方式,

webflux的實現

Swagger2集成Spring boot 2.1.12 基於WebFlux

可以看這篇文章,裏面有詳細的說明

Web的實現

POM的引入

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

配置實現

/**
 * API文檔配置
 * 
 * @author 大仙
 *
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
	@Bean
	public Docket createRestApi(){
		ParameterBuilder builder = new ParameterBuilder();
		builder.parameterType("header").name(Constant.AUTHORIZATION)
		.description("header參數")
		.required(false)
		.modelRef(new ModelRef("string")); // 在swagger裏顯示header
		return new Docket(DocumentationType.SWAGGER_2).groupName("-接口文檔")
				.apiInfo(new ApiInfoBuilder().title("接口文檔")
						.contact(new Contact("朱維", "", "XXX")).version("1.0").build())
				.globalOperationParameters(Lists.newArrayList(builder.build()))
				.select()
				.apis(RequestHandlerSelectors.basePackage("com"))
				.paths(PathSelectors.any()).build();
	}
}

這樣配置完成就OK了

Swagger使用

@Api:用在類上,說明該類的作用。

@ApiOperation:註解來給API增加方法說明。

@ApiImplicitParams : 用在方法上包含一組參數說明。

@ApiImplicitParam:用來註解來給方法入參增加說明。

@ApiResponses:用於表示一組響應

@ApiResponse:用在@ApiResponses中,一般用於表達一個錯誤的響應信息

    l   code:數字,例如400

    l   message:信息,例如"請求參數沒填好"

    l   response:拋出異常的類   

@ApiModel:描述一個Model的信息(一般用在請求參數無法使用@ApiImplicitParam註解進行描述的時候)

    l   @ApiModelProperty:描述一個model的屬性

 

注意:@ApiImplicitParam的參數說明:

paramType:指定參數放在哪個地方

header:請求參數放置於Request Header,使用@RequestHeader獲取

query:請求參數放置於請求地址,使用@RequestParam獲取

path:(用於restful接口)-->請求參數的獲取:@PathVariable

body:(不常用)

form(不常用)

name:參數名

 

dataType:參數類型

 

required:參數是否必須傳

true | false

value:說明參數的意思

 

defaultValue:參數的默認值

 

訪問 

啓動相應的服務之後訪問:http://localhost:端口/swagger-ui.html

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章