1. 程式人生 > >swagger2整合springMvc生成線上API

swagger2整合springMvc生成線上API

在現在的開發中,前後端分離開發越來越明顯,也越來越重要,但是後臺開發人員在開發完介面之後給前端人員或者APP端呼叫,而前端人員或者APP端對介面的作用以及介面中的引數往往不懂,這樣雙方不得不多次溝通交流,很浪費時間。於是就需要一箇中間的工具來無縫連線後臺與前端。

這個中間工具就是今天的主角Swagger。

Swagger 是一個規範和完整的框架,用於生成、描述、呼叫和視覺化 RESTful 風格的 Web 服務。總體目標是使客戶端和檔案系統作為伺服器以同樣的速度來更新。檔案的方法,引數和模型緊密整合到伺服器端的程式碼,允許API來始終保持同步。Swagger 讓部署管理和使用功能強大的API從未如此簡單。

Swagger如何與SpringMvc整合?

整合步驟:

1.引入maven依賴,需要jackson的jar包支援

<!-- swagger -->
<dependency>  
          <groupId>io.springfox</groupId>  
          <artifactId>springfox-swagger2</artifactId>  
         <version>2.4.0</version>  
     </dependency>  
     <dependency>  
            <groupId>io.springfox</groupId>  
            <artifactId>springfox-swagger-ui</artifactId>  
            <version>2.4.0</version>  
        </dependency>
<!-- jackson json -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>2.2.3</version>
</dependency>

2.swagger配置類
package org.zjl.controller.swagger.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

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;

/** 
* 描述:swagger2配置類
* @author zhengjinlei 
* @version 2017年4月19日 下午3:47:58 
*/
@EnableWebMvc
@EnableSwagger2
@ComponentScan(basePackages={"org.zjl.controller.app"}) //需要掃描的包路徑 
@Configuration public class SwaggerApiConfig extends WebMvcConfigurationSupport{ @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Java從業者") .termsOfServiceUrl("") .contact(new Contact("我本碼農", "", "[email protected]")) .version("v1.0") .build(); } }
spring的配置檔案中宣告Validator
<!-- 配置 JSR303 Bean Validator 定義 -->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
3.此時啟動工程,會掃描包中的controller類生成沒有任何說明的API文件

4.如果想要帶有說明的線上API文件,需要在掃描的類中配置一些註解

例如:

package org.zjl.controller.app;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import org.zjl.entity.User;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/** 
* 描述:使用者controller
* @author zhengjinlei 
* @version 2017年4月19日 下午4:01:49 
*/
@Api(value="users")
@RestController  
@RequestMapping(value = "/users") // 通過這裡配置使下面的對映都在/users下,可去除  
public class UserController {  
  
	    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());  
	  
	    @ApiOperation(value = "獲取使用者列表", notes = "")  
	    @RequestMapping(value = { "" }, method = RequestMethod.GET)  
	    public List<User> getUserList() {  
	        List<User> r = new ArrayList<User>(users.values());  
	        return r;  
	    }  
	  
	    @ApiOperation(value = "建立使用者", notes = "根據User物件建立使用者")  
	    @ApiImplicitParam(name = "user", value = "使用者詳細實體user", required = true, dataType = "User")  
	    @RequestMapping(value = "", method = RequestMethod.POST)  
	    public String postUser(@RequestBody User user) {  
	        //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)  
	    public User getUser(@PathVariable Long id) {  
	        return users.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)  
	    public String putUser(@PathVariable Long id, @RequestBody User user) {  
	        User u = 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)  
	    public String deleteUser(@PathVariable Long id) {  
	        users.remove(id);  
	        return "success";  
	    }  
}
註解說明:
@ApiIgnore 忽略註解標註的類或者方法,不新增到API文件中

@ApiOperation 展示每個API基本資訊
	value api名稱
	notes 備註說明
@ApiImplicitParam 用於規定接收引數型別、名稱、是否必須等資訊

	name 對應方法中接收引數名稱
	value 備註說明
	required 是否必須 boolean
	paramType 引數型別 body、path、query、header、form中的一種 
		body 使用@RequestBody接收資料 POST有效
		path 在url中配置{}的引數
		query 普通查詢引數 例如 ?query=q ,jquery ajax中data設定的值也可以,例如 {query:”q”},springMVC中不需要添加註解接收
		header 使用@RequestHeader接收資料
		form 筆者未使用,請檢視官方API文件
	dataType 資料型別,如果型別名稱相同,請指定全路徑,例如 dataType = “java.util.Date”,springfox會自動根據型別生成模型
@ApiImplicitParams 包含多個@ApiImplicitParam

@ApiModelProperty 對模型中屬性新增說明,只能使用在類中。
	value 引數名稱
	required 是否必須 boolean
	hidden 是否隱藏 boolean 
	其他資訊和上面同名屬性作用相同,hidden屬性對於集合不能隱藏,目前不知道原因
@ApiParam 對單獨某個引數進行說明,使用在類中或者controller方法中都可以。註解中的屬性和上面列出的同名屬性作用相同
到此,一個完美的結合線上API文件的工程的完成了,啟動工程,在瀏覽器中輸入http://IP:port/工程名/swagger-ui.html

就可以瀏覽屬於你工程的線上API文件。





相關推薦

swagger2整合springMvc生成線上API

在現在的開發中,前後端分離開發越來越明顯,也越來越重要,但是後臺開發人員在開發完介面之後給前端人員或者APP端呼叫,而前端人員或者APP端對介面的作用以及介面中的引數往往不懂,這樣雙方不得不多次溝通交流,很浪費時間。於是就需要一箇中間的工具來無縫連線後臺與前端。 這個中間工

spring-boot整合swagger生成線上api文件

基本的步驟大致如下: 1.pom中引入swagger依賴: <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swag

SpringBoot 整合swageer2 生成RestFul API文檔

use 用戶 red arraylist enables ces prop clas rip 1.首先建立SpringBoot項目,導入swagger2所用的依賴      <dependency> <groupId>

Spring Boot 整合 swagger2 自動生成 RESTFul API 文檔

pat turn ket config 文件 pen 用戶 配置文件 方式 1)首先編輯pom.xml添加依賴 <dependency>   <groupId>io.springfox</groupId>   <artifactI

Swagger2整合springBoot,自動生成API介面文件

Swagger2整合springBoot 首先匯入jar包 <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swa

整合swagger2生成Restful Api介面文件 webapi文件描述-swagger

整合swagger2生成Restful Api介面文件 swagger Restful文件生成工具 2017-9-30 官方地址:https://swagger.io/docs/specification/about/ 官方Github:https://github.com/swagger-

《深入理解Spring Cloud與微服務構建》學習筆記(七)~SpringBoot 整合 Swagger2,搭建線上api文件

一、在專案 pom.xml 引入 swagger 依賴 springfox-swagger2 和 springfox-swagger-ui 如: <dependency> <groupId>io.springfox</groupId>

基於swagger2生成線上RESTful API HTML文件以及生成離線PDF文件 亂碼 文字丟失 解決辦法

專案基礎 springboot 2.02 springfox-swagger2/springfox-swagger-ui 2.8 io.github.swagger2markup 1.3.3 在需要加入的專案RESTful API HTML文件引入依

swagger2springmvc 整合 生成介面文件

簡介 Swagger 是一個規範和完整的框架,用於生成、描述、呼叫和視覺化 RESTful 風格的 Web 服務。總體目標是使客戶端和檔案系統作為伺服器以同樣的速度來更新。檔案的方法,引數和模型緊密整合到伺服器端的程式碼,允許API來始終保持同步。Swagg

Swagger2+SpringMVC 生成API介面文件

簡單記錄一下配置的過程 - 匯入包 - 寫個配置類 - 在Controller層用註解進行註釋 - 通過一個URL就可以看到api介面文件 jar包

初次嘗試swagger springmvc整合 生成restful api文件

1、maven 所需jar包 <dependency>         <groupId>com.mangofactory</groupId>         <artifactId>swagger-springmvc<

Swagger2springMVC整合測試

inter encoding src mybatis project constrain aop servle efault 對Swagger寫個獨立的工程測試,方便後續進行工程的整合,這裏做一下記錄 1.pom.xml--依賴的的包 1 <project xm

03、Swagger2Springmvc整合詳細記錄(爬坑記錄)

component 效果 ges context tex ron 問題 package amp 時間 內容 備註 2018年6月18日 基本使用 spirngmvc整合swagger2 開始之前這個系列博文基本是,在項目的使用中一些模塊的內容記錄,但是

使用Swagger2構建SpringMVC項目中的Restful API文檔

部署 success 直接 資源 路徑 ng- extends 信息 org 使用Swagger自動生成API文檔,不僅增加了項目的可維護性,還提高了API的透明度更利於快速測試等工作,便於更快地發現和解決問題。 本篇文章只記錄整合過程,關於Security Configu

SpringMVC與Springfox(Swagger2)整合詳解以及涉及的問題處理

        Swagger 是一個規範和完整的框架,用於生成、描述、呼叫和視覺化 RESTful 風格的 Web 服務。總體目標是使客戶端和檔案系統作為伺服器以同樣的速度來更新。檔案的方法,引數和模型緊密整合到伺服器端的程式碼,允許API來始終保持同步

Spring boot 整合 swagger生成api文件(轉換成markdown格式)

spring boot 整合 swagger 步驟 1. 匯入jar包 2. 新增配置類 3. 新增介面類 3. 啟動伺服器 4. 訪問UI頁面,可線上測試介面 5. 匯出swagger原始檔 6. 轉換成markdown格式檔案 1,匯入jar包 gradl

springboot整合Swagger能夠自動生成介面api

1.新增pom <!--swagger2--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</arti

springmvc 與 springfox-swagger2整合

一、pom.xml引入基於maven的swagger依賴      <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-sw

Spring專案整合apidoc生成api介面文件

一、背景需求  JavaWeb/spring專案寫成的api介面,需要自動生成api文件,甚至需要線上測試介面。考慮實現的方案有swagger,apidoc,spring rest docs。在之後的專案都有一一嘗試,最終還是覺得apidoc的方式比較合適,雖然有一些問題(針對線上

【Web】Java生成中文GIF動態驗證碼-整合SpringMVC

說明 GIF驗證碼相對於JPG圖片驗證碼來說,要更難破解一些,加大了破解的代價。 從昨天到現在,寫了一個小小的GIF驗證碼專案(中文成語)。 當然,你可以自己修改成字母數字的。我只是單純的覺得中文驗證碼的破解代價更高一點~ 我在這裡生成GIF圖片