介紹
現如今前後端分離的時代,前端常抱怨後端給的接口文檔與實際情況不一致,後端又覺得編寫及維護接口文檔會耗費不少精力,經常來不及更新,swagger則應運而生,它的優點如下:
- 號稱世界上最流行的API框架
- API 文檔 與API同步更新
- 直接運行,在線測試API
- 官網:https://swagger.io/
- 訪問測試 :http://localhost:8080/swagger-ui.html ,可以看到swagger的界面;
使用
- 導入依賴
<!-- 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>
- 配置
package com.lxs.swagger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
@Configuration
@EnableSwagger2//開啓swagger2
public class SwaggerConfig {
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.groupName("AAA")//分組的名字
.select()
.apis(RequestHandlerSelectors.basePackage("com.lxs.swagger.controller"))//配置掃描指定的包
.build();
}
//配置Swagger信息apiInfo
private ApiInfo apiInfo(){
//作者信息
Contact DEFAULT_CONTACT = new Contact("***", "https://blog.csdn.net/weixin_45954737", "****");
return new ApiInfo(
"**的API文檔",//標題
"這人有點6",//描述
"v1.0",//版本
"https://blog.csdn.net/weixin_45954737",//團隊鏈接
DEFAULT_CONTACT,//聯繫人信息
"Apach 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",//許可鏈接
new ArrayList()
);
}
}
從配置中我們可以注意到Docket類是主要的,而且在配置中還包含一個groupName(),這是對這個docket備註的名字,也就是說可以創建多個docket指定不同的掃描路徑,這也是多人開發時可能會用到,示例如下:
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2).groupName("group1");
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2).groupName("group2");
}
@Bean
public Docket docket3(){
return new Docket(DocumentationType.SWAGGER_2).groupName("group3");
}
當然我們也可以將實體類映射出去,只要這個實體在請求接口的返回值上,都能映射到實體項中
最後就是一些常用註釋
package com.lxs.swagger.controller;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
@Controller
public class SwaggerController {
@ApiOperation("***的接口")
@PostMapping("/hello")
public String Hello(@ApiParam("姓名") String name){
return null;
}
}
下面是註釋的作用
@ApiOperation(“xxx接口說明”) | |
---|---|
@ApiParam(“xxx參數說明”) | |
@ApiModel(“xxxPOJO說明”) |