作爲後臺開發人員,在進行controller接口調試的時候,每次都用postman或者在xml文本里寫form表單進行請求,比較麻煩,後來發現用swagger可以大大的簡化這一過程,現將springboot如何集成進行一下記錄。
1、何爲swagger
Swagger是一款RESTful接口的文檔在線自動生成、功能測試功能框架。一個規範和完整的框架,用於生成、描述、調用和可視化RESTful風格的Web服務,加上swagger-ui,可以有很好的呈現。
2、springboot如何集成swagger
2.1先新建一個springboot工程
可參考上一篇博客:idea創建springboot工程: https://blog.csdn.net/u014429653/article/details/84726466;
eclipse創建springboot工程:https://blog.csdn.net/u014429653/article/details/84722029
2.2創建controller接口,可在瀏覽器訪問
2.2引入swagger對應的jar包
<!--對swagger-ui的支持-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
2.3編寫配置文件
@Configuration
@EnableSwagger2
public class SwaggerConfig {
//是否開啓swagger,正式環境一般是需要關閉的,可根據springboot的多環境配置進行設置
@Value(value = "${swagger.enabled}")
Boolean swaggerEnabled;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
// 是否開啓
.enable(swaggerEnabled).select()
// 掃描的路徑包
.apis(RequestHandlerSelectors.basePackage("com.example.springbootdemo.controller"))
// 指定路徑處理PathSelectors.any()代表所有的路徑
.paths(PathSelectors.any()).build().pathMapping("/");
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SpringBoot-Swagger2集成和使用-demo示例")
.description("wuKong")
// 作者信息
.contact(new Contact("wuKong", "https://blog.csdn.net/u014429653", "郵箱"))
.version("1.0.0")
.build();
}
}
2.4添加文檔內容(一般在Controller請求參數上進行註解)
在類名上添加註釋@Api(tags = “TestController”, description = “測試接口相關”)
在方法名上添加註釋@ApiOperation(value = “進行打招呼戶測試”, notes = “請求返回打招呼的字符串”)
2.5訪問本地swagger地址
http://localhost:8080/swagger-ui.html#/
點擊execute可發起請求
2.6往後臺傳入參數
使用@RequestParam註解
注意:
在方法名上需註釋請求類型method = RequestMethod.GET,否則swagger頁面會生成所有的請求類型
@RequestMapping(value = “/hello1”, method = RequestMethod.GET)