1、pom.xml 引入依賴
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
2、建立swagger配置類
package com.zxx.until;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@EnableWebMvc
@EnableSwagger2 //Loads the spring beans required by the framework
public class MySwaggerConfig {
@Bean
public Docket userApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select() // 選擇那些路徑和api會生成document
.apis(RequestHandlerSelectors.any()) // 對所有api進行監控
// .apis(RequestHandlerSelectors.basePackage("")) 指定監控路徑
.paths(PathSelectors.any()) // 對所有路徑進行監控
.build();
}
}
3、在SpringMVC的Bean中寫入資源路徑映射
<!-- 引入swagger相關 -->
<bean class="com.zxx.controller.MySwaggerConfig"/> <!-- 配置類全路徑 -->
4、改造controller
類上加:
@Api(tags = “student”) 自定義名字,用來描述接口
方法上加: 描述功能和參數 ,例:
@ApiOperation(value=”擷取使用者清單”,notes=”擷取使用者清單”)
@PostMapping(value = “/list002”)
@ApiImplicitParams({
@ApiImplicitParam(name = “name”, value = “姓名”, paramType = “query”, dataType = “String”,required = true),
@ApiImplicitParam(name = “age”, value = “年齡”, paramType = “query”, dataType = “String”,required = true),
@ApiImplicitParam(name = “id”, value = “ID”, paramType = “query”, dataType = “String”),
})
public String queryList(Student user){
System.out.println(“姓名:”+user.getId());
System.out.println(“年齡:”+user.getName());
return “aa”;
}
簡單介紹常用注解
@ApiIgnore 忽略不顯示該接口(類和方法上都可以加)
@PostMapping(value = “/list002”) 發送get請求
@GetMapping(value = “/list002”) 發送post請求
@ApiImplicitParams 參數描述 多個參數需嵌套 @ApiImplicitParam
@ApiImplicitParam 參數描述 隻有一個參數可以直接用
name–參數名
value–參數說明
required = true / false 是否必須輸入
dataType = “String” 參數類型
defaultValue = “” 預設值
allowableValues = “xx,xx,xx” 下拉内容
allowMultiple = true 下拉支援多選
paramType = “query”
path 以位址的形式送出資料
query 直接跟參數完成自動映射指派
body 以流的形式送出 僅支援POST
header 參數在request headers 裡邊送出
form 以form表單的形式送出 僅支援POST
如果直接傳遞對象,可在參數直接加 RequestBody 注解 例:@RequestBody Student student
如果将參數拼到url上 ,例:
@ApiOperation(value = “”, notes = “”)
@PostMapping(value = “queryById/{id}”)
public String getQrcode(@PathVariable String id) {
return “”;
}
5.直接通路 ip+port 自定義
http://localhost:8080/項目名/swagger-ui.html