1. 程式人生 > >Spring boot整合Swagger

Spring boot整合Swagger

multipl required access esp das bject 參考 editor 是我

本文github位置:https://github.com/WillVi/springboot-swagger2-demo

環境準備

  1. JDK版本:1.8
  2. Spring boot版本:1.5.16
  3. Swagger及其Swagger-ui版本:2.6.1(關於swagger-ui版本 每個版本的漢化方式可能有不同)
  4. 默認url:http://localhost:8080/swagger-ui.html

Maven依賴

<!-- swagge2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>
<!-- swaggerui用於展示swagger頁面 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>

註意事項:

swagger-ui依賴 有可能會與com.google.guava沖突 提供一個解決辦法:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.2.2</version>
    <!-- 將沖突包移除 -->
    <exclusions>
        <exclusion>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </exclusion>
    </exclusions>
</dependency>

配置文件

@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket api() {
        // 統一設置返回描述
        List<ResponseMessage> responseMessages = new ArrayList<>();
        responseMessages.add(new ResponseMessageBuilder().code(400).message("請求參數有誤").build());
        responseMessages.add(new ResponseMessageBuilder().code(401).message("未授權").build());
        responseMessages.add(new ResponseMessageBuilder().code(403).message("禁止訪問").build());
        responseMessages.add(new ResponseMessageBuilder().code(404).message("請求路徑不存在").build());
        responseMessages.add(new ResponseMessageBuilder().code(500).message("服務器內部錯誤").responseModel(new ModelRef("string")).build());

        return new Docket(DocumentationType.SWAGGER_2)
                // 禁用默認返回描述
                .useDefaultResponseMessages(false)
                // 啟用新的返回描述
                .globalResponseMessage(RequestMethod.GET, responseMessages)
                .globalResponseMessage(RequestMethod.POST, responseMessages)
                .globalResponseMessage(RequestMethod.PATCH, responseMessages)
                .globalResponseMessage(RequestMethod.PUT, responseMessages)
                .globalResponseMessage(RequestMethod.DELETE, responseMessages)
                // 設置基本信息
                .apiInfo(apiInfo())
                .select()
                // 設置哪些api被掃描
                .apis(RequestHandlerSelectors.basePackage("cn.willvi.springbootswaggerdemo"))
                // 設置路徑
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 設置基本信息
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // 標題
                .title("我的接口文檔")
                // 描述
                .description("這是我的第一個接口文檔")
                // 版本號
                .version("1.0")
                // 項目的鏈接
                .termsOfServiceUrl("")
                // 作者
                .license("willvi")
                .licenseUrl("")
                .build();
    }
}

Swagger註解詳解

@Api 設置Controller整體信息

註解位置:Controller類上

/**
 * value                 url路徑值(漢化後不起作用) http://xxx/swagger-ui.html#/demo-controller中的 demo-controller即為value
 * tags                  設置這個值、value的值會被覆蓋(漢化後有bug最好不寫)
 * description           對api資源的描述
 * basePath              基本路徑可以不配置
 * position              如果配置多個Api 想改變顯示的順序位置
 * produces              例如, "application/json, application/xml"  頁面上的 Response Content Type (響應Content Type)
 * consumes              例如, "application/json, application/xml"
 * protocols             Possible values: http, https, ws, wss.
 * authorizations        高級特性認證時配置
 * hidden                配置為true 將在文檔中隱藏
 */
@Api(value = "Swagger 註解使用",description = "123")

@ApiOperation 設置每個方法(接口)信息

註解位置:方法上

  /**
     * value               頁面tab右側值
     * tags                如果設置這個值、value的值會被覆蓋
     * description         對api資源的描述
     * basePath            基本路徑可以不配置
     * position            如果配置多個Api 想改變顯示的順序位置
     * produces            例如, "application/json, application/xml"
     * consumes            例如, "application/json, application/xml"
     * protocols           Possible values: http, https, ws, wss.
     * authorizations      高級特性認證時配置
     * hidden              配置為true 將在文檔中隱藏
     * response            返回的對象
     * responseContainer   這些對象是有效的 "List", "Set" or "Map".,其他無效
     * httpMethod  "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH"
     * code                http的狀態碼 默認 200
     * extensions          擴展屬性
     */
     @ApiOperation(
            value = "post",
            notes = "這是一個小demo",
            produces = "application/json",
            response = Person.class
    )

@ApiImplicitParams 與 @ApiImplicitParam 設置傳入參數信息

註解位置:方法上

註意事項: name必須與參數名相同,不然多出一個參數框

    /**
     * @ApiImplicitParam
     * 當dataType不是對象時可以使用
     *
     * paramType:參數放在哪個地方
     * name:參數代表的含義
     * value:參數名稱
     * dataType: 參數類型,有String/int,無用
     * required : 是否必要
     * defaultValue:參數的默認值
     */
    @ApiImplicitParams(
            @ApiImplicitParam(name = "name",value = "name",paramType ="path", dataType = "String")
    )

@ApiResponses 設置返回的一些狀態碼信息

註解位置:方法上

 /**
     * code                http的狀態碼
     * message             描述
     * response            默認響應類 Void
     * reference           參考ApiOperation中配置
     * responseHeaders     參考 ResponseHeader 屬性配置說明
     * responseContainer   參考ApiOperation中配置
     */
@ApiResponses({@ApiResponse(code = 500, message = "服務器內部錯誤", response = String.class)})

@ApiModel

描述一個Model的信息(這種一般用在post創建的時候,使用@RequestBody這樣的場景,請求參數無法使用@ApiImplicitParam註解進行描述的時候

註解位置:實體類上

@ApiModelProperty

描述一個model的屬性。

註解位置:實體類每個屬性上面

@ApiModelProperty(value = "姓名",name = "name")

@ApiParam

註解位置:方法參數內

 /**
     * name 屬性名稱
     * value    屬性值
     * defaultValue 默認屬性值
     * allowableValues  可以不配置
     * required 是否屬性必填
     * access   不過多描述
     * allowMultiple    默認為false
     * hidden   隱藏該屬性
     * example  舉例子
     */
 public ResponseEntity<String> placeOrder(
      @ApiParam(value = "xxxx", required = true) Person person) {
    storeData.add(order);
    return ok("");
  }

Controler示例

@Api(value = "Swagger 註解使用")

@RestController
@RequestMapping("/")


public class DemoController {
    @PostMapping("/postHello")
    /**
     * value               url的路徑值
     * tags                如果設置這個值、value的值會被覆蓋
     * description         對api資源的描述
     * basePath            基本路徑可以不配置
     * position            如果配置多個Api 想改變顯示的順序位置
     * produces            例如, "application/json, application/xml"
     * consumes            例如, "application/json, application/xml"
     * protocols           Possible values: http, https, ws, wss.
     * authorizations      高級特性認證時配置
     * hidden              配置為true 將在文檔中隱藏
     * response            返回的對象
     * responseContainer   這些對象是有效的 "List", "Set" or "Map".,其他無效
     * httpMethod  "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH"
     * code                http的狀態碼 默認 200
     * extensions          擴展屬性
     */
    @ApiOperation(
            value = "post",
            notes = "這是一個小demo",
            produces = "application/json",
            response = Person.class
    )
    /**
     * code                http的狀態碼
     * message             描述
     * response            默認響應類 Void
     * reference           參考ApiOperation中配置
     * responseHeaders     參考 ResponseHeader 屬性配置說明
     * responseContainer   參考ApiOperation中配置
     */
    @ApiResponses({@ApiResponse(code = 500, message = "服務器內部錯誤", response = String.class)})
    public ResponseEntity<Person> postHello(@RequestBody Person person){
        return ResponseEntity.ok(person);
    }

    @GetMapping("/hello/{name}")
    @ApiOperation(
            value = "hello world",
            notes = "這是一個小demo"
    )
    /**
     * @ApiImplicitParam
     * 當dataType不是對象時可以使用
     * paramType:參數放在哪個地方
     * name:參數代表的含義
     * value:參數名稱
     * dataType: 參數類型,有String/int,無用
     * required : 是否必要
     * defaultValue:參數的默認值
     */
    @ApiImplicitParams(
            @ApiImplicitParam(value = "name",paramType ="path", dataType = "String",defaultValue = "world")
    )
    public String hello(@PathVariable String name){
        return "hello " + name;
    }
}

Model示例

// 描述一個Model的信息
@ApiModel
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Person {
    @ApiModelProperty(value = "姓名",name = "name")
    String name;
    int age;
}

swagger漢化

  1. 在resources資源下創建 META-INF/resources 文件夾並創建名為swagger-ui.html文件

  2. 復制以下內容:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Swagger UI</title>
        <link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-32x32.png" sizes="32x32"/>
        <link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-16x16.png" sizes="16x16"/>
        <link href=‘webjars/springfox-swagger-ui/css/typography.css‘ media=‘screen‘ rel=‘stylesheet‘ type=‘text/css‘/>
        <link href=‘webjars/springfox-swagger-ui/css/reset.css‘ media=‘screen‘ rel=‘stylesheet‘ type=‘text/css‘/>
        <link href=‘webjars/springfox-swagger-ui/css/screen.css‘ media=‘screen‘ rel=‘stylesheet‘ type=‘text/css‘/>
        <link href=‘webjars/springfox-swagger-ui/css/reset.css‘ media=‘print‘ rel=‘stylesheet‘ type=‘text/css‘/>
        <link href=‘webjars/springfox-swagger-ui/css/print.css‘ media=‘print‘ rel=‘stylesheet‘ type=‘text/css‘/>
    
        <script src=‘webjars/springfox-swagger-ui/lib/object-assign-pollyfill.js‘ type=‘text/javascript‘></script>
        <script src=‘webjars/springfox-swagger-ui/lib/jquery-1.8.0.min.js‘ type=‘text/javascript‘></script>
        <script src=‘webjars/springfox-swagger-ui/lib/jquery.slideto.min.js‘ type=‘text/javascript‘></script>
        <script src=‘webjars/springfox-swagger-ui/lib/jquery.wiggle.min.js‘ type=‘text/javascript‘></script>
        <script src=‘webjars/springfox-swagger-ui/lib/jquery.ba-bbq.min.js‘ type=‘text/javascript‘></script>
        <script src=‘webjars/springfox-swagger-ui/lib/handlebars-4.0.5.js‘ type=‘text/javascript‘></script>
        <script src=‘webjars/springfox-swagger-ui/lib/lodash.min.js‘ type=‘text/javascript‘></script>
        <script src=‘webjars/springfox-swagger-ui/lib/backbone-min.js‘ type=‘text/javascript‘></script>
        <script src=‘webjars/springfox-swagger-ui/swagger-ui.min.js‘ type=‘text/javascript‘></script>
        <script src=‘webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack.js‘ type=‘text/javascript‘></script>
        <script src=‘webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack_extended.js‘ type=‘text/javascript‘></script>
        <script src=‘webjars/springfox-swagger-ui/lib/jsoneditor.min.js‘ type=‘text/javascript‘></script>
        <script src=‘webjars/springfox-swagger-ui/lib/marked.js‘ type=‘text/javascript‘></script>
        <script src=‘webjars/springfox-swagger-ui/lib/swagger-oauth.js‘ type=‘text/javascript‘></script>
    
        <script src=‘webjars/springfox-swagger-ui/springfox.js‘ type=‘text/javascript‘></script>
        <!-- 漢化 -->
        <script src=‘webjars/springfox-swagger-ui/lang/translator.js‘ type=‘text/javascript‘></script>
        <script src=‘webjars/springfox-swagger-ui/lang/zh-cn.js‘ type=‘text/javascript‘></script>
    </head>
    
    <body class="swagger-section">
    <div id=‘header‘>
        <div class="swagger-ui-wrap">
            <a id="logo" href="http://swagger.io"><img class="logo__img" alt="swagger" height="30" width="30" src="webjars/springfox-swagger-ui/images/logo_small.png" /><span class="logo__title">swagger</span></a>
            <form id=‘api_selector‘>
                <div class=‘input‘>
                    <select id="select_baseUrl" name="select_baseUrl"/>
                </div>
                <div class=‘input‘><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>
                <div id=‘auth_container‘></div>
                <div class=‘input‘><a id="explore" class="header__btn" href="#" data-sw-translate>Explore</a></div>
            </form>
        </div>
    </div>
    
    <div id="message-bar" class="swagger-ui-wrap" data-sw-translate>&nbsp;</div>
    <div id="swagger-ui-container" class="swagger-ui-wrap"></div>
    </body>
    </html>
  3. 訪問即可

Spring boot整合Swagger