springMVC整合swagger2

1、What is swagger?

官方介紹Swagger是一個規範且完整的框架,提供描述、生產、消費和可視化RESTful Web Service。
專業角度:Swagger是由龐大工具集合支撐的形式化規範。這個集合涵蓋了從終端用戶接口、底層代碼庫到商業API管理的方方面面。html

2、Why use the swagger?

  1. 講個故事:在2014年時候,我和另外一個小夥伴加入到一個實驗室,開始了咱們漫長的應用開發之路(這也是第一次作項目)。由於只有兩我的,我作後臺,他作Android,分工很明確的。在一開始,咱們並無關注API相關的內容,隨手拈來,我說什麼,他就調用什麼。固然,也沒有什麼API文檔提供。以致於到如今,我想更新升級系統,才發現,咱們寫的代碼是有多爛,連本身都不忍心去看的。因此說在項目開始就定一個契約,雙方(前端後臺)就API相關的內容,包括路徑、參數、類型等達成一致,固然,這份契約並非一旦建立就不能修改的,並且,若是一開始沒有設計好,頗有可能會頻繁的修改。
  2. 做爲一個很懶的碼代碼的猿呢,對於一些API的理解老是很模糊不清,可是,總想着能直接驗證一下本身的理解就行了,而不是須要去項目寫測試代碼來驗證本身的想法。因此說,API文檔應該有直接運行的能力。而Swagger就是這樣的一個東西,它能夠爲已有項目的生成具有執行能力的樣式化API文檔,這樣能夠極大的方便程序員對前端後臺進行對接整合。

3、use the swagger

0.Spring MVC配置文件中的配置

<!-- 設置使用註解的類所在的jar包,只加載controller類 -->  前端

  1. <span style="white-space:pre">    </span><context:component-scan base-package="com.jay.plat.config.controller" />   
  2. <!-- 使用 Swagger Restful API文檔時,添加此註解 -->  
  3.     <mvc:default-servlet-handler />  

1.maven依賴

  1. <!-- 構建Restful API -->  
  2.           
  3.         <dependency>  
  4.             <groupId>io.springfox</groupId>  
  5.             <artifactId>springfox-swagger2</artifactId>  
  6.             <version>2.4.0</version>  
  7.         </dependency>  
  8.         <dependency>  
  9.             <groupId>io.springfox</groupId>  
  10.             <artifactId>springfox-swagger-ui</artifactId>  
  11.             <version>2.4.0</version>  
  12.         </dependency>  

2.Swagger配置文件

packagecom.jay.plat.config.util;

        importorg.springframework.context.annotation.Bean;
        importorg.springframework.context.annotation.ComponentScan;
        importorg.springframework.context.annotation.Configuration;
        importorg.springframework.web.servlet.config.annotation.EnableWebMvc;
        importorg.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
        importspringfox.documentation.builders.ApiInfoBuilder;
        importspringfox.documentation.builders.PathSelectors;
        importspringfox.documentation.builders.RequestHandlerSelectors;
        importspringfox.documentation.service.ApiInfo;
        importspringfox.documentation.spi.DocumentationType;
        importspringfox.documentation.spring.web.plugins.Docket;
        importspringfox.documentation.swagger2.annotations.EnableSwagger2;

/*
*RestfulAPI訪問路徑:
*http://IP:port/{context-path}/swagger-ui.html
*eg:http://localhost:8080/jd-config-web/swagger-ui.html
*/
@EnableWebMvc
@EnableSwagger2
@ComponentScan(basePackages = {"com.<spanstyle="font - family:Arial, Helvetica, sans-serif;">jay.</span>plat.config.controller"})
@Configuration
publicclassRestApiConfigextendsWebMvcConfigurationSupport{

@Bean
publicDocketcreateRestApi(){
        returnnewDocket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.jay.plat.config.controller"))
        .paths(PathSelectors.any())
        .build();
        }

        privateApiInfoapiInfo(){
        returnnewApiInfoBuilder()
        .title("Spring中使用Swagger2構建RESTfulAPIs")
        .termsOfServiceUrl("http://blog.csdn.net/he90227")
        .contact("逍遙飛鶴")
        .version("1.1")
        .build();
        }
}

 

配置說明:java

 

  1. @Configuration 配置註解,自動在本類上下文加載一些環境變量信息  
  2. @EnableWebMvc   
  3. @EnableSwagger2 使swagger2生效  
  4. @ComponentScan("com.myapp.packages") 須要掃描的包路徑  

3.Controller中使用註解添加API文檔

packagecom.jay.spring.boot.demo10.swagger2.controller;

        importjava.util.ArrayList;
        importjava.util.Collections;
        importjava.util.HashMap;
        importjava.util.List;
        importjava.util.Map;

        importorg.springframework.web.bind.annotation.PathVariable;
        importorg.springframework.web.bind.annotation.RequestBody;
        importorg.springframework.web.bind.annotation.RequestMapping;
        importorg.springframework.web.bind.annotation.RequestMethod;
        importorg.springframework.web.bind.annotation.RestController;

        importcom.jay.spring.boot.demo10.swagger2.bean.User;

        importio.swagger.annotations.ApiImplicitParam;
        importio.swagger.annotations.ApiImplicitParams;
        importio.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = "/users")//經過這裏配置使下面的映射都在/users下,可去除
publicclassUserController{

        staticMap<Long, User>users=Collections.synchronizedMap(newHashMap<Long, User>());

@ApiOperation(value = "獲取用戶列表", notes = "")
@RequestMapping(value = {""}, method = RequestMethod.GET)
        publicList<User>getUserList(){
        List<User>r=newArrayList<User>(users.values());
        returnr;
        }

@ApiOperation(value = "建立用戶", notes = "根據User對象建立用戶")
@ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User")
@RequestMapping(value = "", method = RequestMethod.POST)
        publicStringpostUser(@RequestBodyUseruser){
        users.put(user.getId(),user);
        return"success";
        }

@ApiOperation(value = "獲取用戶詳細信息", notes = "根據url的id來獲取用戶詳細信息")
@ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
        publicUsergetUser(@PathVariableLongid){
        returnusers.get(id);
        }

@ApiOperation(value = "更新用戶詳細信息", notes = "根據url的id來指定更新對象,並根據傳過來的user信息來更新用戶詳細信息")
@ApiImplicitParams({@ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long"),
        @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User")})
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
        publicStringputUser(@PathVariableLongid,@RequestBodyUseruser){
        Useru=users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id,u);
        return"success";
        }

@ApiOperation(value = "刪除用戶", notes = "根據url的id來指定刪除對象")
@ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long")
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
        publicStringdeleteUser(@PathVariableLongid){
        users.remove(id);
        return"success";
        }

        }


4.效果展現程序員

 

  1. Restful API 訪問路徑:  
  2.  * http://IP:port/{context-path}/swagger-ui.html  
  3.  * eg:http://localhost:8080/jd-config-web/swagger-ui.html  

參考http://blog.csdn.net/jia20003/article/details/50700736web

相關文章
相關標籤/搜索