1. 程式人生 > 其它 >Visual Studio 擴充套件入門(三)HelloWorld 下篇

Visual Studio 擴充套件入門(三)HelloWorld 下篇

新增Maven依賴

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>

寫一個配置類-SwaggerConfig來配置 Swagger

@Configuration//配置類
@EnableSwagger2// 開啟Swagger2的自動配置
publicclassSwaggerConfig{
}
訪問測試 :http://localhost:8080/swagger-ui.html,可以看到swagger的介面;

1、Swagger例項Bean是Docket,所以通過配置Docket例項來配置Swaggger。

@Bean
publicDocketdocket(Environmentenvironment) {
// 設定要顯示swagger的環境
Profilesof=Profiles.of("dev","test");
// 判斷當前是否處於該環境
// 通過 enable() 接收此引數判斷是否要顯示
booleanb=environment.acceptsProfiles(of);

returnnewDocket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(b)//配置是否啟用Swagger,如果是false,在瀏覽器將無法訪問
.select()// 通過.select()方法,去配置掃描介面,RequestHandlerSelectors配置如何掃描介面
.apis(RequestHandlerSelectors.basePackage("com.lyy.swagger.controller"))
// 配置如何通過path過濾,即這裡只掃描請求以/kuang開頭的介面
.paths(PathSelectors.ant("/lyy/**"))
.build();
}

2、可以通過apiInfo()屬性配置文件資訊

//配置文件資訊
privateApiInfoapiInfo() {
Contactcontact=newContact("聯絡人名字","http://xxx.xxx.com/聯絡人訪問連結","聯絡人郵箱");
returnnewApiInfo(
"Swagger學習",// 標題
"學習演示如何配置Swagger",// 描述
"v1.0",// 版本
"http://terms.service.url/組織連結",// 組織連結
contact,// 聯絡人資訊
"Apach 2.0 許可",// 許可
"許可連結",// 許可連線
newArrayList<>()// 擴充套件
);
}

配置API分組

@Bean
publicDocketdocket1(){
returnnewDocket(DocumentationType.SWAGGER_2).groupName("group1");
}
@Bean
publicDocketdocket2(){
returnnewDocket(DocumentationType.SWAGGER_2).groupName("group2");
}
@Bean
publicDocketdocket3(){
returnnewDocket(DocumentationType.SWAGGER_2).groupName("group3");
}

常用註解

Swagger的所有註解定義在io.swagger.annotations包下

下面列一些經常用到的,未列舉出來的可以另行查閱說明:

Swagger註解簡單說明
@Api(tags = "xxx模組說明") 作用在模組類上
@ApiOperation("xxx介面說明") 作用在介面方法上
@ApiModel("xxxPOJO說明") 作用在模型類上:如VO、BO
@ApiModelProperty(value = "xxx屬性說明",hidden = true) 作用在類方法和屬性上,hidden設定為true可以隱藏該屬性
@ApiParam("xxx引數說明") 作用在引數、方法和欄位上,類似@ApiModelProperty