1. 程式人生 > >Spring集成Swagger,Java自動生成Api文檔

Spring集成Swagger,Java自動生成Api文檔

jar包 depend pan restful can nic -a src 構建

博主很懶...

Swagger官網:http://swagger.io

GitHub地址:https://github.com/swagger-api

官方註解文檔:http://docs.swagger.io/swagger-core/apidocs/index.html

Swagger-UI地址:https://github.com/swagger-api/swagger-ui

swagger最終效果圖

技術分享圖片

好,開始說Spring怎麽配置Swagger了

1.pom.xml引入需要的jar包

<!-- 構建Restful API 我這版本是2.6.1 -->
<dependency>
    <
groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${swagger2.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <
version>${swagger2.version}</version> </dependency>

2.掃描你的Swagger2config.java所在的包

<!-- url是你需要掃描swagger的包路徑 -->
<context:component-scan  base-package="com.nickwilde.microtrain.common.config.swagger"/>

3.Swagger2config.java[類名自定義]

package com.nickwilde.microtrain.common.config.swagger2;

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @author NickWilde * @version 2018/1/18 10:23 * @description: Swagger2Config * TODO 用一句話描述 */ @Configuration @EnableSwagger2 public class Swagger2Config{ @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2).forCodeGeneration(true) .select() .apis(RequestHandlerSelectors.any()) //過濾生成鏈接 .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } //api接口作者相關信息 private ApiInfo apiInfo() { Contact contact = new Contact("NickWilde", "", "[email protected]"); ApiInfo apiInfo = new ApiInfoBuilder() .license("Apache License Version 2.0") .title("Unexpectedly系統") .description("接口文檔") .contact(contact) .version("1.0") .build(); return apiInfo; } }

4.給你的controller加上額外註解(不加也是有的)

@ApiOperation(value="根據User對象創建用戶", notes="根據User對象創建用戶",httpMethod = "POST") //httpMehtod如果不定義,那麽swagger會有把該接口的所有請求方法都一一列舉出來
@ApiImplicitParam(name = "data", value = "data描述", required = true, dataType = "UserInfo") //參數定義..類型..之類的,這是基礎簡單,其余的看api吧~

Spring集成Swagger,Java自動生成Api文檔