SpringBoot整合Swagger2


相信各位在公司寫API文檔數量應該不少,當然如果你還處在自己一個人開發前后台的年代,當我沒說,如今為了前后台更好的對接,還是為了以后交接方便,都有要求寫API文檔。

 

手寫Api文檔的幾個痛點:

  1. 文檔需要更新的時候,需要再次發送一份給前端,也就是文檔更新交流不及時。
  2. 接口返回結果不明確
  3. 不能直接在線測試接口,通常需要使用工具,比如postman
  4. 接口文檔太多,不好管理

Swagger也就是為了解決這個問題,當然也不能說Swagger就一定是完美的,當然也有缺點,最明顯的就是代碼移入性比較強。

其他的不多說,想要了解Swagger的,可以去Swagger官網,可以直接使用Swagger editor編寫接口文檔,當然我們這里講解的是SpringBoot整合Swagger2,直接生成接口文檔的方式。

一、依賴

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

二、Swagger配置類

其實這個配置類,只要了解具體能配置哪些東西就好了,畢竟這個東西配置一次之后就不用再動了。 特別要注意的是里面配置了api文件也就是controller包的路徑,不然生成的文檔掃描不到接口。

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    /**
     * 創建API
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                // 用來創建該API的基本信息,展示在文檔的頁面中(自定義展示的信息)
                .apiInfo(apiInfo())
                // 設置哪些接口暴露給Swagger展示
                .select()
                // 掃描所有有注解的api,用這種方式更靈活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 掃描指定包中的swagger注解
                // .apis(RequestHandlerSelectors.basePackage("com.ruoyi.project.tool.swagger"))
                // 掃描所有 .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any()).build();
    }

    /**
     * 添加摘要信息
     */
    private ApiInfo apiInfo() {
        // 用ApiInfoBuilder進行定制
        return new ApiInfoBuilder()
                // 設置標題
                .title("標題:若依管理系統_接口文檔")
                // 描述
                .description("描述:用於管理集團旗下公司的人員信息,具體包括XXX,XXX模塊...")
                // 作者信息
                .contact(new Contact(Global.getName(), null, null))
                // 版本
                .version("版本號:" + Global.getVersion()).build();
    }
}

用@Configuration注解該類,等價於XML中配置beans;用@Bean標注方法等價於XML中配置bean。

Application.class 加上注解@EnableSwagger2 表示開啟Swagger

package cn.saytime;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
public class SpringbootSwagger2Application {

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

三、Restful 接口

package cn.saytime.web;

import cn.saytime.bean.JsonResult;
import cn.saytime.bean.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
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 springfox.documentation.annotations.ApiIgnore;

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

/**
 * @author zh
 * @ClassName cn.saytime.web.UserController
 * @Description
 */
@RestController
public class UserController {

    // 創建線程安全的Map
    static Map<Integer, User> users = Collections.synchronizedMap(new HashMap<Integer, User>());

    /**
     * 根據ID查詢用戶
     * @param id
     * @return
     */
    @ApiOperation(value="獲取用戶詳細信息", notes="根據url的id來獲取用戶詳細信息")
    @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Integer", paramType = "path")
    @RequestMapping(value = "user/{id}", method = RequestMethod.GET)
    public ResponseEntity<JsonResult> getUserById (@PathVariable(value = "id") Integer id){
        JsonResult r = new JsonResult();
        try {
            User user = users.get(id);
            r.setResult(user);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }

    /**
     * 查詢用戶列表
     * @return
     */
    @ApiOperation(value="獲取用戶列表", notes="獲取用戶列表")
    @RequestMapping(value = "users", method = RequestMethod.GET)
    public ResponseEntity<JsonResult> getUserList (){
        JsonResult r = new JsonResult();
        try {
            List<User> userList = new ArrayList<User>(users.values());
            r.setResult(userList);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }

    /**
     * 添加用戶
     * @param user
     * @return
     */
    @ApiOperation(value="創建用戶", notes="根據User對象創建用戶")
    @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User")
    @RequestMapping(value = "user", method = RequestMethod.POST)
    public ResponseEntity<JsonResult> add (@RequestBody User user){
        JsonResult r = new JsonResult();
        try {
            users.put(user.getId(), user);
            r.setResult(user.getId());
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");

            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }

    /**
     * 根據id刪除用戶
     * @param id
     * @return
     */
    @ApiOperation(value="刪除用戶", notes="根據url的id來指定刪除用戶")
    @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long", paramType = "path")
    @RequestMapping(value = "user/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<JsonResult> delete (@PathVariable(value = "id") Integer id){
        JsonResult r = new JsonResult();
        try {
            users.remove(id);
            r.setResult(id);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");

            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }

    /**
     * 根據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 ResponseEntity<JsonResult> update (@PathVariable("id") Integer id, @RequestBody User user){
        JsonResult r = new JsonResult();
        try {
            User u = users.get(id);
            u.setUsername(user.getUsername());
            u.setAge(user.getAge());
            users.put(id, u);
            r.setResult(u);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");

            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }

    @ApiIgnore//使用該注解忽略這個API
    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    public String  jsonTest() {
        return " hi you!";
    }
}

Json格式輸出類 JsonResult.class

package cn.saytime.bean;

public class JsonResult {

    private String status = null;

    private Object result = null;

    // Getter Setter
}

實體User.class

package cn.saytime.bean;

import java.util.Date;

/**
 * @author zh
 * @ClassName cn.saytime.bean.User
 * @Description
 */
public class User {

    private int id;
    private String username;
    private int age;
    private Date ctm;

    // Getter Setter
}

四、Swagger2文檔

啟動SpringBoot項目,訪問 http://localhost:8080/swagger-ui.html

運行項目,這個時候可能會報這個錯,如下所示

2018-05-28 14:40:56.887 ERROR [main] o.s.boot.SpringApplication - Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerAdapter' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Initialization of bean failed; nested exception is java.lang.NoSuchMethodError: com.google.common.collect.FluentIterable.toList()Lcom/google/common/collect/ImmutableList;
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107)
    at com.qtay.gls.Application.main(Application.java:24)
Caused by: java.lang.NoSuchMethodError: com.google.common.collect.FluentIterable.toList()Lcom/google/common/collect/ImmutableList;
    at springfox.documentation.spring.web.ObjectMapperConfigurer.jackson2Converters(ObjectMapperConfigurer.java:76)
    at springfox.documentation.spring.web.ObjectMapperConfigurer.configureMessageConverters(ObjectMapperConfigurer.java:63)
    at springfox.documentation.spring.web.ObjectMapperConfigurer.postProcessBeforeInitialization(ObjectMapperConfigurer.java:47)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:409)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1620)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    ... 15 common frames omitted

Process finished with exit code 1

在網上搜索了下,加入下面這段代碼就OK了!

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.8.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.8.0</version>
</dependency>
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>25.1-jre</version>
</dependency>

五、Swagger注解

swagger通過注解表明該接口會生成文檔,包括接口名、請求方法、參數、返回信息的等等。

  • @Api:修飾整個類,描述Controller的作用
  • @ApiOperation:描述一個類的一個方法,或者說一個接口
  • @ApiParam:單個參數描述
  • @ApiModel:用對象來接收參數
  • @ApiProperty:用對象接收參數時,描述對象的一個字段
  • @ApiResponse:HTTP響應其中1個描述
  • @ApiResponses:HTTP響應整體描述
  • @ApiIgnore:使用該注解忽略這個API
  • @ApiError :發生錯誤返回的信息
  • @ApiImplicitParam:一個請求參數
  • @ApiImplicitParams:多個請求參數


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM