日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

spring-boot-swagger2 使用手冊

 WindySky 2017-09-12

在項(xiàng)目中常用的注解說明

注解 屬性 備注
@Api value 字符串 可用在class頭上,class描述
  description 字符串  
      @Api(value = "xxx", description = "xxx")
@ApiOperation value 字符串 可用在方法頭上.參數(shù)的描述容器
  notes 字符串  
      @ApiOperation(value = "xxx", notes = "xxx")
@ApiImplicitParams {} @ApiImplicitParam數(shù)組 可用在方法頭上.參數(shù)的描述容器
      @ApiImplicitParams({@ApiImplicitParam1,@ApiImplicitParam2,...})
@ApiImplicitParam name 字符串 與參數(shù)命名對應(yīng) 可用在@ApiImplicitParams
  value 字符串 參數(shù)中文描述
  required 布爾值 true/false
  dataType 字符串 參數(shù)類型
  paramType 字符串 參數(shù)請求方式:query/path
      query:對應(yīng)@RequestParam?傳遞
      path: 對應(yīng)@PathVariable{}path傳遞
  defaultValue 字符串 在api測試中默認(rèn)值
      用例參見項(xiàng)目中的設(shè)置
@ApiResponses {} @ApiResponse數(shù)組 可用在方法頭上.參數(shù)的描述容器
      @ApiResponses({@ApiResponse1,@ApiResponse2,...})
@ApiResponse code 整形 可用在@ApiResponses
  message 字符串 錯誤描述
      @ApiResponse(code = 200, message = "Successful")

1.Demo結(jié)構(gòu)

Maven pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven./POM/4.0.0"
         xmlns:xsi="http://www./2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven./POM/4.0.0 http://maven./xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.reachauto.hkr.cxn</groupId>
    <artifactId>cxn-demo-swagger2</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-parent</artifactId>
        <version>Angel.SR6</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!-- Swagger -->
       <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
        </dependency>
        <!-- END Swagger -->

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

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項(xiàng)目 Platform API",//大標(biāo)題
                initContextInfo(),//簡單的描述
                "1.0.0",//版本
                "服務(wù)條款",
                "后臺開發(fā)團(tuán)隊",//作者
                "The Apache License, Version 2.0",//鏈接顯示文字
                "http://www.baidu.com"http://網(wǎng)站鏈接
        );

        return apiInfo;
    }

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

        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,最終調(diào)用接口后會和paths拼接在一起
                .select()
                .paths(doFilteringRules())
                .build()
                .apiInfo(initApiInfo());
    }

    /**
     * 設(shè)置過濾規(guī)則
     * 這里的過濾規(guī)則支持正則匹配
     * @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;

/**
 * Created by cxn on 2016/2/24.
 */
@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標(biāo)簽<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 = "未授權(quán)客戶機(jī)訪問數(shù)據(jù)"),
            @ApiResponse(code = 404, message = "服務(wù)器找不到給定的資源;文檔不存在"),
            @ApiResponse(code = 500, message = "服務(wù)器不能完成請求")}
    )
    @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 = "根據(jù)車牌查詢車輛", notes = "這種類型的查詢是精確查詢,其結(jié)果只有一條數(shù)據(jù)", 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 = "未授權(quán)客戶機(jī)訪問數(shù)據(jù)"),
            @ApiResponse(code = 404, message = "服務(wù)器找不到給定的資源;文檔不存在"),
            @ApiResponse(code = 500, message = "服務(wù)器不能完成請求")}
    )
    @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 = "根據(jù)車牌查詢車輛位置信息", 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 = "未授權(quán)客戶機(jī)訪問數(shù)據(jù)"),
            @ApiResponse(code = 404, message = "服務(wù)器找不到給定的資源;文檔不存在"),
            @ApiResponse(code = 500, message = "服務(wù)器不能完成請求")}
    )
    @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 = "根據(jù)車輛id查詢", notes = "精確查詢,最常規(guī)的方式,支持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 = "未授權(quán)客戶機(jī)訪問數(shù)據(jù)"),
            @ApiResponse(code = 404, message = "服務(wù)器找不到給定的資源;文檔不存在"),
            @ApiResponse(code = 500, message = "服務(wù)器不能完成請求")}
    )
    @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 = "根據(jù)車輛id查詢", notes = "精確查詢,最常規(guī)的方式,支持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 = "服務(wù)器拒絕請求"),
            @ApiResponse(code = 401, message = "未授權(quán)客戶機(jī)訪問數(shù)據(jù)"),
            @ApiResponse(code = 404, message = "服務(wù)器找不到給定的資源;文檔不存在"),
            @ApiResponse(code = 500, message = "服務(wù)器不能完成請求")}
    )
    @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 = "網(wǎng)點(diǎn)掛靠", notes = "嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻嘻", response = String.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successful — 請求已完成"),
            @ApiResponse(code = 400, message = "請求中有語法問題,或不能滿足請求"),
            @ApiResponse(code = 401, message = "未授權(quán)客戶機(jī)訪問數(shù)據(jù)"),
            @ApiResponse(code = 404, message = "服務(wù)器找不到給定的資源;文檔不存在"),
            @ApiResponse(code = 500, message = "服務(wù)器不能完成請求")}
    )
    @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("網(wǎng)點(diǎn)掛靠", 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);
    }
}

2.演示地址

http://localhost:8080/api/v1/swagger-ui.html

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多