SpringFox Swagger2注解基本用法


一切參數說明,參考官方API文檔:http://docs.swagger.io/swagger-core/current/apidocs/index.html?io/swagger/annotations

在實體和API注釋這塊,有些注釋不一定在頁面上表現,但是接口返回的數據上全部都有返回。

Swagger2出自SpringFOX, 官網:https://github.com/springfox/springfox,而與https://swagger.io/不同,所以在https://swagger.io/上是找不到Swagger2的開發文檔。

在Swagger2的GitHUb頁面上也沒提供相關的詳細文檔,不過可以參考示例代碼庫https://github.com/springfox/springfox-demos進行參考。

不過下面這些網址還能找到關於Swagger的先關API文檔,並且兼容Swagger2的:

http://docs.swagger.io/swagger-core/current/apidocs/index.html

https://github.com/swagger-api/swagger-core(舊版示例)

https://github.com/swagger-api/swagger-core/wiki/Annotations-1.5.X#quick-annotation-overview

https://github.com/swagger-api/swagger-samples(新版示例)

下面是收集的一些常用注解,如果要更多的用法,可以參照上面官網提供的文檔:

名稱 描述
@Api 將類標記為Swagger資源。
@ApiImplicitParam 表示API操作中的單個參數。
@ApiImplicitParams 允許多個ApiImplicitParam對象列表的包裝器。
@ApiModel 提供有關Swagger型號的其他信息。
@ApiModelProperty 添加和操作模型屬性的數據。
@ApiOperation 描述針對特定路徑的操作或通常的HTTP方法。
@ApiParam 為操作參數添加額外的元數據。
@ApiResponse 描述操作的可能響應。
@ApiResponses 允許多個ApiResponse對象列表的包裝器。
@Authorization 聲明在資源或操作上使用授權方案。
@AuthorizationScope 描述OAuth2授權范圍。
@ResponseHeader 表示可以作為響應的一部分提供的頭。

示例代碼:

SwaggerConfig 配置

import com.google.common.base.Predicate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import static com.google.common.base.Predicates.or;
import static springfox.documentation.builders.PathSelectors.regex;

/**
 * SwaggerConfig
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Value("${server.servlet-path}")
    private String pathMapping;

    private ApiInfo initApiInfo() {
        ApiInfo apiInfo = new ApiInfo("XXX項目 Platform API",//大標題
                initContextInfo(),//簡單的描述
                "1.0.0",//版本
                "服務條款",
                "后台開發團隊",//作者
                "The Apache License, Version 2.0",//鏈接顯示文字
                "http://www.baidu.com"//網站鏈接
        );

        return apiInfo;
    }

    private String initContextInfo() {
        StringBuffer sb = new StringBuffer();
        sb.append("REST API 設計在細節上有很多自己獨特的需要注意的技巧,並且對開發人員在構架設計能力上比傳統 API 有着更高的要求。")
                .append("<br/>")
                .append("本文通過翔實的敘述和一系列的范例,從整體結構,到局部細節,分析和解讀了為了提高易用性和高效性,REST API 設計應該注意哪些問題以及如何解決這些問題。");

        return sb.toString();
    }


    @Bean
    public Docket restfulApi() {
        System.out.println("http://localhost:8080" + pathMapping + "/swagger-ui.html");

        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("RestfulApi")
//                .genericModelSubstitutes(DeferredResult.class)
                .genericModelSubstitutes(ResponseEntity.class)
                .useDefaultResponseMessages(true)
                .forCodeGeneration(false)
                .pathMapping(pathMapping) // base,最終調用接口后會和paths拼接在一起
                .select()
                .paths(doFilteringRules())
                .build()
                .apiInfo(initApiInfo());
    }

    /**
     * 設置過濾規則
     * 這里的過濾規則支持正則匹配
     * @return
     */
    private Predicate<String> doFilteringRules() {
        return or(
                regex("/hello.*"),
                regex("/vehicles.*")
        );
    }
}

Controller 的配置

import com.reachauto.hkr.cxn.swagger.bean.ChangeRentalShopParameter;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Api(value = "API - VehiclesController", description = "車輛模塊接口詳情")
@RestController
@RequestMapping("/vehicles")
public class VehiclesController {

    private static Logger logger = LoggerFactory.getLogger(VehiclesController.class);


    @ApiOperation(value = "查詢車輛接口", notes = "此接口描述xxxxxxxxxxxxx<br/>xxxxxxx<br>值得慶幸的是這兒支持html標簽<hr/>", response = String.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "vno", value = "車牌", required = false,
                    dataType = "string", paramType = "query", defaultValue = "遼A12345"),
            @ApiImplicitParam(name = "page", value = "page", required = false,
                    dataType = "Integer", paramType = "query",defaultValue = "1"),
            @ApiImplicitParam(name = "count", value = "count", required = false,
                    dataType = "Integer", paramType = "query",defaultValue = "10")
    })
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successful — 請求已完成"),
            @ApiResponse(code = 400, message = "請求中有語法問題,或不能滿足請求"),
            @ApiResponse(code = 401, message = "未授權客戶機訪問數據"),
            @ApiResponse(code = 404, message = "服務器找不到給定的資源;文檔不存在"),
            @ApiResponse(code = 500, message = "服務器不能完成請求")}
    )
    @ResponseBody
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ModelMap findVehicles(@RequestParam(value = "vno", required = false) String vno,
                                 @RequestParam(value = "page", required = false) Integer page,
                                 @RequestParam(value = "count", required = false) Integer count)
            throws Exception {

        logger.info("http://localhost:8501/api/v1/vehicles");
        logger.info("## {},{},{}", vno, page, count);
        logger.info("## 請求時間:{}", new Date());

        ModelMap map = new ModelMap();
        map.addAttribute("vno", vno);
        map.addAttribute("page", page);
        return map;
    }


    @ApiOperation(value = "根據車牌查詢車輛", notes = "這種類型的查詢是精確查詢,其結果只有一條數據", response = String.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "vno", value = "車牌", required = false,
                    dataType = "string", paramType = "path", defaultValue = "遼A12345")
    })
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successful — 請求已完成"),
            @ApiResponse(code = 400, message = "請求中有語法問題,或不能滿足請求"),
            @ApiResponse(code = 401, message = "未授權客戶機訪問數據"),
            @ApiResponse(code = 404, message = "服務器找不到給定的資源;文檔不存在"),
            @ApiResponse(code = 500, message = "服務器不能完成請求")}
    )
    @ResponseBody
    @RequestMapping(value = "vno={vno}", method = RequestMethod.GET)
    public ModelMap getVno(@PathVariable(value = "vno") String vno)
            throws Exception {

        logger.info("http://localhost:8501/api/v1/vehicles/vno={}", vno);
        logger.info("## 請求時間:{}", new Date());

        ModelMap map = new ModelMap();
        map.addAttribute("vno", vno);

        return map;
    }

    @ApiOperation(value = "車輛位置查詢接口", notes = "根據車牌查詢車輛位置信息", response = String.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "vno", value = "車牌", required = false,
                    dataType = "string", paramType = "path", defaultValue = "遼A12345")
    })
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successful — 請求已完成"),
            @ApiResponse(code = 400, message = "請求中有語法問題,或不能滿足請求"),
            @ApiResponse(code = 401, message = "未授權客戶機訪問數據"),
            @ApiResponse(code = 404, message = "服務器找不到給定的資源;文檔不存在"),
            @ApiResponse(code = 500, message = "服務器不能完成請求")}
    )
    @ResponseBody
    @RequestMapping(value = "vno={vno}/location", method = RequestMethod.GET)
    public ModelMap getLocation(@PathVariable(value = "vno") String vno)
            throws Exception {
        logger.info("getLocation");
        logger.info("## 請求時間:{}", new Date());

        ModelMap map = new ModelMap();
        map.addAttribute("vno", vno);

        return map;
    }


    @ApiOperation(value = "根據車輛id查詢", notes = "精確查詢,最常規的方式,支持POST和GET方式", response = String.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = false,
                    dataType = "string", paramType = "path", defaultValue = "12344444")
    })
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successful — 請求已完成"),
            @ApiResponse(code = 400, message = "請求中有語法問題,或不能滿足請求"),
            @ApiResponse(code = 401, message = "未授權客戶機訪問數據"),
            @ApiResponse(code = 404, message = "服務器找不到給定的資源;文檔不存在"),
            @ApiResponse(code = 500, message = "服務器不能完成請求")}
    )
    @ResponseBody
    @RequestMapping(value = "{id}", method = {RequestMethod.GET,RequestMethod.POST})
    public ModelMap getById(@PathVariable(value = "id") String id)
            throws Exception {

        logger.info("http://localhost:8501/api/v1/vehicles/{}", id);
        logger.info("## 請求時間:{}", new Date());

        ModelMap map = new ModelMap();
        map.addAttribute("{RequestMethod.GET,RequestMethod.POST}", id);

        return map;
    }
@ApiOperation(value
= "根據車輛id查詢", notes = "精確查詢,最常規的方式,支持POST和GET方式", response = String.class) @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "string", paramType = "path", defaultValue = "12344444") }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful — 請求已完成"), @ApiResponse(code = 400, message = "請求中有語法問題,或不能滿足請求"), @ApiResponse(code = 403, message = "服務器拒絕請求"), @ApiResponse(code = 401, message = "未授權客戶機訪問數據"), @ApiResponse(code = 404, message = "服務器找不到給定的資源;文檔不存在"), @ApiResponse(code = 500, message = "服務器不能完成請求")} ) @ResponseBody @RequestMapping(value = "{id}", method = {RequestMethod.DELETE}) public ModelMap delById(@PathVariable(value = "id") String id) throws Exception { logger.info("http://localhost:8501/api/v1/vehicles/{}", id); logger.info("## 請求時間:{}", new Date()); ModelMap map = new ModelMap(); map.addAttribute("RequestMethod.DELETE", id); return map; } @ApiOperation(value = "網點掛靠", notes = "嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻", response = String.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful — 請求已完成"), @ApiResponse(code = 400, message = "請求中有語法問題,或不能滿足請求"), @ApiResponse(code = 401, message = "未授權客戶機訪問數據"), @ApiResponse(code = 404, message = "服務器找不到給定的資源;文檔不存在"), @ApiResponse(code = 500, message = "服務器不能完成請求")} ) @ResponseBody @RequestMapping(value = "change_rentalshop", method = {RequestMethod.PUT,RequestMethod.PATCH}) public ModelMap changeRentalShop(@RequestBody ChangeRentalShopParameter parameter) throws Exception { logger.info("http://localhost:8501/api/v1/vehicles/change_rentalshop | {}", parameter); logger.info("## 請求時間:{}", new Date()); ModelMap map = new ModelMap(); map.addAttribute("網點掛靠", new Date()); return map; } }

Application 啟動模塊

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

示例代碼輸出的效果:

 

測試工程:https://github.com/easonjim/5_java_example/tree/master/swagger2test/test1

 

參考:

https://springframework.guru/spring-boot-restful-api-documentation-with-swagger-2/

https://gumutianqi1.gitbooks.io/specification-doc/content/tools-doc/spring-boot-swagger2-guide.html(以上內容部分轉自此篇文章)

http://blog.csdn.net/xupeng874395012/article/details/68946676

http://blog.csdn.net/z28126308/article/details/71126677

http://blog.csdn.net/u014231523/article/details/76522486

http://blog.csdn.net/fanpeng1100/article/details/54016292


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM