如果你所在的公司的還沒有使用swagger甚至沒有聽說過swagger,趕快學習一下我的這篇博客吧,五分鐘速成,傻瓜式的集成,但就是這么簡單的應(yīng)用一定會讓他們震驚到的。
首先對swagger做一個簡介吧:swagger是后臺開發(fā)的神器,也是前后端交流的渠道。你可以用swagger做什么?首先,你以后基本可以告別單元測試了;其次,你不用再寫接口文檔了,也不需要寫完之后再去對文檔進行維護了。swagger可以完全模擬http請求,入?yún)⒊鰠⒑蛯嶋H情況差別幾乎為零。說了這些,直接來干貨吧!
集成四部曲:
第一步:導入兩個依賴吧,如果你不是maven項目,那你去找找jar包吧,記住只需要兩個,我看別的教程引入了七八個,簡直是浪費。
1
2
3
4
5
6
7
8
9
10
|
<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> |
第二步:添加一個類(拷貝下面的即可,注意修改包名,地址)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
/** * Swagger配置 * * @author wq * @since 2017-05-16 */ @EnableWebMvc @EnableSwagger2 @Configuration public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage( "com.z*.b*.c*.controller" )) // 注意修改此處的包名 .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title( "接口列表 v1.1.0" ) // 任意,請稍微規(guī)范點 .description( "接口測試" ) // 任意,請稍微規(guī)范點 .termsOfServiceUrl( "http://url/swagger-ui.html" ) // 將“url”換成自己的ip:port .contact( "laowu" ) // 無所謂(這里是作者的別稱) .version( "1.1.0" ) .build(); } } |
第三步:在mvc的配置的文件中添加下面配置,可能你的文件也許是叫 dispatcher.xml!(照抄即可,完全不需要修改)
1
2
|
<mvc:resources mapping= "swagger-ui.html" location= "classpath:/META-INF/resources/" /> <mvc:resources mapping= "/webjars/**" location= "classpath:/META-INF/resources/webjars/" /> |
第四步:在方法和參數(shù)上添加注解
方法上:
@ApiOperation(value = "教程", httpMethod = "POST", notes = "教程")
放在入?yún)⒅校?br />
@ApiParam(required = true, name = "test", value = "教程入?yún)?quot;)
擔心有些朋友還不太明白,放張圖吧!
第五步:啟動服務(wù),然后在瀏覽器輸入:
http://ip:port/swagger-ui.html
出現(xiàn)下面的畫面就代表大功告成:
注意事項:如果你的項目中使用了攔截器,請將swagger資源放行(還是可以直接拷貝下面的配置,全部,不要懷疑v2)
1
2
3
|
<mvc:exclude-mapping path= "/swagger*/**" ></mvc:exclude-mapping> <mvc:exclude-mapping path= "/v2/**" ></mvc:exclude-mapping> <mvc:exclude-mapping path= "/webjars/**" ></mvc:exclude-mapping> |
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://blog.csdn.net/BlackMambaProgrammer/article/details/72354007