Spring boot整合Swagger

本文github位置:github.com/WillVi/spri…

環境準備

  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衝突 提供一個解決辦法:javascript

<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類上css

/** * 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 設置每一個方法(接口)信息

註解位置:方法上html

/** * 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 設置傳入參數信息

註解位置:方法上java

注意事項: name必須與參數名相同,否則多出一個參數框jquery

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

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

註解位置:方法上git

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

@ApiModel

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

註解位置:實體類上web

@ApiModelProperty

描述一個model的屬性。spring

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

@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. 訪問便可

相關文章
相關標籤/搜索