官方文檔:
swagger是一個前后端api統一文檔和測試框架,注意,不光是一個api文檔,還可以測試
- 怎么使用呢 這里慢慢道來,我們一般用的都是maven工程,所以這里直接上maven依賴
<swagger.version>1.5.8</swagger.version>
<io.springfox.version>2.5.0</io.springfox.version>
<!-- swagger start -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-core</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${io.springfox.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${io.springfox.version}</version>
</dependency>
<!-- swagger end -->
- 這里我們需要注入SwaggerConfiguration配置,直接上代碼
/** * Created by max on 8/16/16. * */ @EnableSwagger2 public class SwaggerConfiguration { @Bean public Docket getApiInfo() { return new Docket(DocumentationType.SWAGGER_2) .groupName("outer api") .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() .apiInfo(outApiInfo()); } private ApiInfo outApiInfo() { return new ApiInfo( "mylearn 前后端接口-外部", // title 標題 "外部接口文檔", // description 描述 標題下 "1.0.0", // version "http://mylearn/*", // termsOfService new Contact("xieyuebin","","xieyuebin@meituan.com"), // contact "Apache 2.0", // licence "http://www.apache.org/licenses/LICENSE-2.0.html" // licence url ); } @Bean public UiConfiguration getUiConfig() { return new UiConfiguration( null,// url,暫不用 "none", // docExpansion => none | list "alpha", // apiSorter => alpha "schema", // defaultModelRendering => schema UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS, false, // enableJsonEditor => true | false true); // showRequestHeaders => true | false }
這是對於文檔的說明以及ui的一些配置
- 然后我們還需要把swagger和spring mvc結合起來,首先在web.xml里加入swagger文檔的訪問路徑:
<!-- swagger ui 的靜態資源交由default處理--> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/swagger-ui.html</url-pattern> </servlet-mapping>
- 然后我們在dispatch-servlet.xml里加入對swagger靜態資源jar包的訪問路徑如下:
<!-- swagger 配置 ,線上版本需要注釋掉 --> <beans:bean class="com.meituan.maxtse.mylearn.swagger.SwaggerConfiguration"/> <!-- swagger ui resources--> <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars"/>
這里我們用到了我們前面定義的SwaggerConfiguration類
- 然后我們在controller和請求參數和返回參數里加入swagger提供的注解,直接上例子
入參:
/** * Created by max on 10/11/16. */ @ApiModel(description = "用戶請求表單") public class UserForm { @ApiModelProperty(value = "姓名", example = "maxTse",position = 1) private String username; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public String toString() { return "UserForm{" + "username='" + username + '\'' + '}'; } }
返回值:
@JsonInclude(JsonInclude.Include.NON_NULL) @ApiModel public class OutResult<T> implements Serializable { @ApiModelProperty(value = "數據", example = "") public T data; @ApiModelProperty(value = "狀態碼,0表示成功 其他表示失敗", example = "0") public int status; @ApiModelProperty(value = "錯誤信息", example = "操作成功") public String message = "";
controller:
/** * Created by max on 8/16/16. */ @Controller @RequestMapping(value = "/test", consumes = "application/json", produces = "application/json") public class TestController { private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class); @ApiOperation(value = "swagger test", notes = "swagger test first", tags = {SwaggerConstants.TEST_TAG}) @ResponseBody @RequestMapping(value = "/first", method = RequestMethod.POST) public OutResult<String> first(@RequestBody UserForm userForm) { LOGGER.info("first userForm={}", userForm); throw new RuntimeException("dd"); /* return OutResult.successResult(userForm.getUsername()); */ }
這里挨個注解解釋下:
@ApiModel 表明這是一個被swagger框架管理的model,用於class上
@ApiModelProperty 這里顧名思義,就是標注在被標注了@ApiModel的class的屬性上,
這里的value是對字段的描述,example是取值例子,注意這里的example很有用,對於前后端開發工程師理解文檔起到了關鍵的作用,因為會在api文檔頁面上顯示出這些取值來;這個注解還有一些字段取值,可以自己研究,舉例說一個:position,表明字段在model中的順序
@ApiOperation標注在具體請求上,value和notes的作用差不多,都是對請求進行說明;tags則是對請求進行分類的,比如你有好幾個controller,分別屬於不同的功能模塊,那這里我們就可以使用tags來區分了,看上去很有條理
- 下面我們啟動項目,然后通過url:localhost:8080/swagger-ui.html來訪問,就可以看到swagger文檔界面了
這里是請求和返回結果的界面,看到這個界面是不是對剛才我們貼出來的具體例子里的注解上的每個值有所了解了,一一對應便能了解他們的作用
我們開始說了,這個不僅可以當文檔使,而且還可以進行測試,沒錯,看看參數界面大家都知道了,實際上參數界面就在請求和返回結果的下面:
看到右上方的大紅框,就是我們的入參格式,注意,這里是json格式的
然后我們可以在具體填入自己的請求參數后,點擊下方的try it out按鈕,就可以進行測試了。
總結:
使用swagger2.0框架大概這么幾步:
1.添加maven依賴
2.編寫SwaggerConfiguration配置
3.web.xml里添加swagger文檔的訪問路徑,是靜態資源
4.添加相關的spring mvc配置
5.在請求的入參和返回值 以及具體的請求上添加相應的注解
6.啟動項目,訪問swagger.html
注意:
由於這里使用的是json格式的入參和返回值,那么我們在controller的請求參數那里要加上@RequestBody注解,並且請求方法必須是post