spring boot 整合swagger2 實現動態生成接口文檔

背景介紹

在以往的項目開發中,項目的接口文檔通常以word的形式,互相傳閱。可是具備如下缺點:html

1.接口更新了,文檔沒更新java

2.系統版本多,接口版本也不少,很差管理web

3.測試接口時,一般會使用postman等,http調試工具,若是接口url寫錯,或者某個必傳參數遺漏,就會致使接口測試失敗,比較繁瑣。spring

Swagger有什麼用?

swagger是一個流行的API開發框架,這個框架以「開放API聲明」(OpenAPI Specification,OAS)爲基礎, json

對整個API的開發週期都提供了相應的解決方案,是一個很是龐大的項目(包括設計、編碼和測試,幾乎支持全部語言)。api

Swagger 是一個規範和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。 瀏覽器

整體目標是使客戶端和文件系統做爲服務器以一樣的速度來更新。 springboot

文件的方法,參數和模型緊密集成到服務器端的代碼,容許API來始終保持同步。Swagger 讓部署管理和使用功能強大的API從未如此簡單。服務器

swagger2在系統中的主要做用,就是以註解的方式,侵入接口,動態生成可視化接口文檔(swagger-ui)。mvc

總體效果以下:

这里写图片描述

接口詳情:

这里写图片描述

咱們能夠在這個文檔中,完成對接口的調用測試。

SpringBoot 與 Swagger2

因爲java的強大的註解功能,咱們使用SpringBoot來結合Swagger2,在使用起來很是簡單. 

因爲Spring的流行,Marty Pitt編寫了一個基於Spring的組件swagger-springmvc,用於將swagger集成到springmvc中來。

pom文件添加依賴

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>

建立api

@Controller
@RequestMapping("user")
public class UserController {
	@RequestMapping(value = "/hello", method = RequestMethod.GET)
	public String hello() {
		return "hello";
	}
}

建立Swagger2配置類

package com.example.demo.utils;

import org.springframework.beans.factory.annotation.Value;
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
public class SwaggerConfig {
	/**
	 * 能夠經過變量設置swagger-ui是否顯示,好比測試環境能夠暴露api文檔,生產環境咱們就關閉
	 */
	@Value("${swagger.enable}")
	private boolean enableSwagger;

	/**
	 * 固定寫法,設置須要掃描的接口類,通常是controller,或者特定的api類 
	 * enable(enableSwagger)控制接口文檔的ui的開關
	 */
	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).enable(enableSwagger).select()
				.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")).paths(PathSelectors.any())
				.build();
	}
	/**
	 * 在構建接口文檔ui時,能夠動態的顯示一些咱們這裏添加的提示信息
	 */
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder().title("springboot利用swagger構建api文檔").description("rest api 文檔構建利器")
				.termsOfServiceUrl("測試url").contact("taizhu").version("1.0").build();
	}
}

@Configuration // 定義配置類,加入到spring配置中去

以上的三個方法,爲固定寫法。

給啓動類添加註解

@EnableSwagger2 // 開啓swagger2註解功能

@ComponentScan(basePackages = { "com.example.demo.controller", "com.example.demo.service",
		"com.example.demo.datasource" })
@EnableAutoConfiguration
@EnableSwagger2
public class Demo1Application {

	public static void main(String[] args) {
		SpringApplication.run(Demo1Application.class, args);
	}

}

這時候,咱們啓動項目,訪問:http://localhost/swagger-ui.html,就能夠看到初步的接口API文檔啦

 

 

Swagger2 註解使用

咱們在UserController中增長一個不用傳遞參數的接口

@RestController
@RequestMapping(value = "/user", produces = "application/json")
@Api(description = "用戶管理")
public class UserController {

	@RequestMapping(value = "/hello", method = RequestMethod.GET)
	public String hello() {
		return "hello";
	}

	ArrayList<User> users = new ArrayList<>();

	@ApiOperation(value = "獲取用戶列表", notes = "獲取全部用戶信息")
	@RequestMapping(value = "/getAll", method = RequestMethod.GET)
	public List<User> getAll() {
		users.add(new User(1, "luoji", 23));
		users.add(new User(2, "yewenjie", 24));
		return users;
	}
}

能夠在接口文檔中看到該接口

能夠看到返回結果的字段類型,而且能夠測試接口,獲取到返回的結果。

可是咱們若是想選擇性的忽略某個字段,而不是把User類中的全部字段暴露出去呢?彆着急,咱們可使用另外一個註解:

@ApiModelProperty(hidden = true)

此註解能夠做用在字段或者方法上,只要 hidden 屬性爲 true ,該字段或者方法就不會被生成api文檔.

目前咱們的ui頁面中,接口顯示參數的類型,可是沒有字段的說明,識別起來很困難,仍是不要着急,咱們也有辦法解決:

@ApiModelProperty(value = "用戶名") 

value屬性指明瞭該字段的含義(描述 Description),再次刷新瀏覽器試試:

以下:
 

package com.example.demo.model;

import io.swagger.annotations.ApiModelProperty;

public class User {
	@ApiModelProperty(hidden = true)
	private int id;
	@ApiModelProperty(value = "用戶名")
	private String name;
	@ApiModelProperty(value = "年齡")
	private int age;

	public User() {
		super();
	}

	public User(int id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

那咱們再次查看swagger-ui頁面,發現id字段,不在接口文檔中暴露了。

這時咱們建立一個新的insert接口,用來接收對象類型的參數。

咱們能夠看到由於以前給實體類添加的@ApiModelProperty(value = "用戶名")註解和 @ApiModelProperty(hidden = true)註解生效了。

參數不單提示類型,還有備註,並且不須要對外暴露的參數,也不會暴露出來。

 

此時,咱們在建立一個接口,經過url來接收參數:

@ApiOperation(value = "查詢用戶", notes = "查詢用戶信息")
	@ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Integer", paramType = "path")
	@RequestMapping(value = "/query/{id}", method = RequestMethod.GET)
	public Integer query(@PathVariable(value = "id") Integer id) {
		return id;
	}

啓動項目。打開swagger-ui頁面,測試接口,查看是否返回了傳入參數。

OK,接口接收到了頁面傳入參數,而且正確返回,測試經過。

最後,咱們建立一個複雜的參數接口,即要接收url傳參,又要接收一個對象類型傳參

package com.example.demo.controller;

import java.util.ArrayList;
import java.util.List;

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

import com.example.demo.model.User;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = "/user", produces = "application/json")
@Api(description = "用戶管理")
public class UserController {

	@RequestMapping(value = "/hello", method = RequestMethod.GET)
	public String hello() {
		return "hello";
	}

	ArrayList<User> users = new ArrayList<>();

	@ApiOperation(value = "獲取用戶列表", notes = "獲取全部用戶信息")
	@RequestMapping(value = "/getAll", method = RequestMethod.GET)
	public List<User> getAll() {
		users.add(new User(1, "luoji", 23));
		users.add(new User(2, "yewenjie", 24));
		return users;
	}

	@ApiOperation(value = "新增用戶", notes = "新增用戶信息")
	@RequestMapping(value = "/insert", method = RequestMethod.GET)
	public User insert(User user) {
		users.add(user);
		return user;
	}

	@ApiOperation(value = "查詢用戶", notes = "查詢用戶信息")
	@ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Integer", paramType = "path")
	@RequestMapping(value = "/query/{id}", method = RequestMethod.GET)
	public Integer query(@PathVariable(value = "id") Integer id) {
		return id;
	}

	/**
	 * 根據id修改用戶信息
	 * 
	 * @param user
	 * @return
	 */
	@ApiOperation(value = "更新信息", notes = "根據url的id來指定更新用戶信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long", paramType = "path"),
			@ApiImplicitParam(name = "user", value = "用戶實體user", required = true, dataType = "User") })
	@RequestMapping(value = "user/{id}", method = RequestMethod.PUT)
	public User update(@PathVariable("id") Integer id, User user) {
		return user;
	}

}

啓動項目,打開swagger-ui頁面,對新接口進行調用

調用成功!

swagger2中的註解:

swagger經過註解代表該接口會生成文檔,包括接口名、請求方法、參數、返回信息的等等,如: 

@ApiIgnore:使用註解忽略該API,不會參與文檔生成

@ApiOperation:描述該api,如: @ApiOperation(value=」建立用戶」, notes=」根據User對象建立用戶」)

請求方法:@RequestMapping(value = 「user」, method = RequestMethod.POST)

參數x信息:@ApiImplicitParam(name = 「user」, value = 「用戶詳細實體user」, required = true, dataType = 「User」)

@Api:修飾整個類,描述Controller的做用

@ApiParam:單個參數描述

@ApiModel:用對象來接收參數

@ApiResponses:HTTP響應總體描述

@ApiProperty:用對象接收參數時,描述對象的一個字段

Swagger2 基本使用(重點加粗顯示):

@Api: 描述類/接口的主要用途

@ApiOperation: 描述方法用途

@ApiImplicitParam: 描述方法的參數

@ApiImplicitParams: 描述方法的參數(Multi-Params)

能夠在上面 建立用戶的方法上添加 @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User")試試看.

@ApiParam:請求屬性

@ApiIgnore: 忽略某類/方法/參數的文檔

注意與 @ApiModelProperty(hidden = true)不一樣, @ApiIgnore 不能用在模型數據上

@ApiResponse:響應配置

如: @ApiResponse(code = 400, message = "無效的用戶信息") ,注意這只是在 生成的Swagger文檔上有效,不要和實際的客戶端調用搞混了. 
一般咱們都是統一JSON返回,用不到這個註解

@ApiResponses:響應集配置

@ResponseHeader: 響應頭設置

例如: @ResponseHeader(name=」head1」,description=」response head conf」)

@ApiModelProperty:添加和操做模型屬性的數據

Swagger-ui頁面的漢化

簡單的說,就是spring boot 會優先讀取resource下面的靜態資源。因此將依賴的swagger-ui的jar包裏面的swagger-ui.html,拷貝出來,並放在

src/main/resources/META-INF/resources 路徑下,而後在頁面中,引入咱們另外在下載到本地的漢化版的js文件

這樣子,每次在打開swagger-ui.html時,都會打開本地的頁面,從而加載本地引入的漢化js,達到漢化效果。

漢化的具體請百度。下面是一個漢化後的效果。

相關文章
相關標籤/搜索