IDEA下載swagger插件
File -> settings -> Plugins 搜索swagger並安裝
pom文件添加依賴
<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>
Swagger配置類
@Configuration
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//掃描包的路徑
.apis(RequestHandlerSelectors.basePackage("com.jpa"))
.paths(PathSelectors.any())
.build();
}
//構建 api文檔的詳細信息函數
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//頁面標題
.title("springboot利用swagger構建api文檔")
//創建人
.contact("chegnjia")
//版本號
.version("1.0")
//描述
.description("API 描述")
.build();
}
}
開啓swagger
在啓動類上添加@EnableSwagger2註解,開啓swagger
@SpringBootApplication
@ComponentScan("com.jpa")//開啓spring註解掃描
@EnableJpaRepositories(basePackages = {"com.jpa.repository"})//掃描JPA資源庫
@EntityScan(basePackages = {"com.jpa.entity"})//掃描實體類
@EnableSwagger2//開啓swagger
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
此時啓動項目就可以訪問http://localhost:8080/swagger-ui.html頁面查看掃描路徑下的接口文檔了,只是因爲項目中沒有使用相關注解而沒有任何註釋。
swagger2 常用註解(非必要)
@Api放在類上面
@Api(description = "測試JPA接口")
public class BookController {
...
}
效果:
@ApiOperation使用在接口上
@ApiOperation(value = "測試接口hello",notes = "用於測試項目能否運行")
@PostMapping("hello")
public String hello(){
return "wellcome!";
}
效果:
@ApiImplicitParam 與 @ApiImplicitParams
@ApiImplicitParam註解用於表明前端傳入的name參數的名字,value是對參數的註釋,example是樣例參數,required是否爲必需項,以及dataType參數類型,以及paramType傳遞方式(query表示使用url問號的方式傳參,這種比較常用,如果使用formData的方式進行傳參,那麼paramType的值爲 form)。
當有多個參數時,需要用@ApiImplicitParams將@ApiImplicitParam包起來
@ApiOperation(value = "測試使用jpa實現分頁功能")
@ApiImplicitParams({
@ApiImplicitParam(name = "page",value = "當前頁碼",example = "1",required = false,dataType = "int",paramType = "query"),
@ApiImplicitParam(name = "size",value = "每頁顯示的數量",example = "5",required = false,dataType = "int",paramType = "query")
})
@PostMapping("noQuery")
public Page<BookEntity> findBookNoQuery(Integer page,Integer size){
....
}
效果:
如果傳遞的是pojo類型的參數
在ui.html中
這裏的Data Type爲 Model,此時我們可以在實體類的代碼中添加註解,選擇我們需要在這裏顯示的屬性。如下:
@ApiModelProperty(hidden = true)表示不需要在swagger頁面進行展示,required表示該屬性爲必需的屬性。