springboot 整合Swagger2的使用

Swagger2相較於傳統Api文檔的優勢

手寫Api文檔的幾個痛點:

文檔須要更新的時候,須要再次發送一份給前端,也就是文檔更新交流不及時。
接口返回結果不明確
不能直接在線測試接口,一般須要使用工具,好比postman
接口文檔太多,很差管理
Swagger也就是爲了解決這個問題,固然也不能說Swagger就必定是完美的,固然也有缺點,最明顯的就是代碼移入性比較強。
能夠直接使用Swagger editor編寫接口文檔,咱們這裏講解的是SpringBoot整合Swagger2,直接生成接口文檔的方式。
依賴文件html

<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>

配置類前端

package com.boss.hr.train.fishkkmybatis.config;

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;

/**
 * @author fishkk
 * @version 1.0.0
 * @since
 */
@Configuration
public class Swagger2Configuration {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.boss.hr.train.fishkkmybatis.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot利用swagger構建api文檔")
                .description("fishkk的Swagger")
                .version("1.0")
                .build();
    }

}

在啓動函數出天價@EnableSwagger2,到這裏就能夠正常的使用Swagger2 了java

Swagger2 的具體使用
package com.boss.hr.train.fishkkmybatis.controller;

import com.boss.hr.train.fishkkmybatis.annotation.Logg;
import com.boss.hr.train.fishkkmybatis.entity.Dictionary;
import com.boss.hr.train.fishkkmybatis.entity.Result;
import com.boss.hr.train.fishkkmybatis.enums.DictionaryEnum;
import com.boss.hr.train.fishkkmybatis.exception.BaseException;
import com.boss.hr.train.fishkkmybatis.service.impl.DictionaryServiceImpl;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author fishkk
 * @version 1.0.0
 * @since 2019/7/27
 */
@RestController
@RequestMapping(value = "/dic")
@CrossOrigin
public class DictionaryController {
    /**
     * Redis 緩存
     */
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private DictionaryServiceImpl dictionaryService;

    private List<Dictionary> list;

    /**
     *  建立字典實體
     * @author fishkk
     * @since  2017/7/25
     * @param  dictionary 字典實體
     * @return  Dictionary 放回建立的字典實體
     */
    @ApiOperation(value="建立字典", notes="根據Dictionary對象建立字典")
    @ApiImplicitParam(name = "dictionary", value = "字典詳細實體dictionary", required = true, dataType = "Dictionary")
    @PostMapping(value = "/insert")
    public Result insertDic(@Valid Dictionary dictionary, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return Result.error(DictionaryEnum.ERROR_INPUT);
        }
        dictionaryService.insert(dictionary);
        return Result.success(dictionary);
    }

    /**
     *  根據主鍵查找字典
     * @author fishkk
     * @since  2019/7/25
     * @param  id 主鍵id
     * @return dictionary查找到的實體對象
     */
    @ApiOperation(value = "獲取字典信息",notes = "根據id獲取字典信息")
    @ApiImplicitParam(name = "id",value = "字典id",required = true, dataType = "Long", paramType = "path")
    @GetMapping(value = "/dic")
    public Result findById(@RequestParam(value = "id") Integer id){
        if (list == null){
            list = dictionaryService.selectAll();
            for (Dictionary x:list) {
                long time = new Random().nextInt(10);
                redisTemplate.opsForValue().set(x.getCategoryId(),x,12,TimeUnit.HOURS);
            }
        }
        if (redisTemplate.opsForValue().get(id) != null){
            return Result.success(redisTemplate.opsForValue().get(id));
        }
        redisTemplate.opsForValue().set(id,dictionaryService.selectByPrimaryKey(id),12,TimeUnit.HOURS);
        return Result.success(dictionaryService.selectByPrimaryKey(id));

    }

    /**
     * 根據主鍵刪除字典
     * @author fishkk
     * @since  2019/7/25
     * @param  id 字典主鍵
     */
    @ApiOperation(value = "根據id刪除單個字典表",notes = "根據id刪除字典")
    @ApiImplicitParam(name = "id",value = "用戶id",required = true, dataType = "Long", paramType = "path")
    @GetMapping(value = "/remove/{id}")
    public Result deleteById(@PathVariable("id") Integer id){
        dictionaryService.deleteByPrimaryKey(id);
        return Result.success(null);
    }

    /**
     *  更新字典對象
     * @author fishkk
     * @since  2019/7/26
     * @param  dictionary 修改過的字典對象
     */
    @ApiOperation(value="更新字典", notes="根據Dictionary更新對應的字典")
    @ApiImplicitParam(name = "dictionary", value = "字典詳細實體dictionary", required = true, dataType = "Dictionary")
    @PostMapping(value = "/updata")
    public Result updata(@Valid Dictionary dictionary, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return Result.error(DictionaryEnum.ERROR_INPUT);
        }
        dictionaryService.updateByPrimaryKey(dictionary);
        return Result.success(null);
    }

    /**
      *  根據字典名查詢
      * @author fishkk
      * @since  2019/7/28
      * @param  name 字典名
      */
    @GetMapping(value = "/get/{name}")
    public Result findByName(@PathVariable("name") String name ){
        return Result.success(dictionaryService.findByName(name));
    }

    /**
     *  根據字典類型查詢
     * @author fishkk
     * @since  2019/7/28
     * @param type 字典類型
     */
    @GetMapping(value = "/gettype/{type}")
    public Result findByType(@PathVariable("type") String type){
        return Result.success(dictionaryService.findByType(type));
    }

    /**
     *  獲取所有對象
     * @author fishkk
     * @since  2019/7/28
     */
    @Logg
    @GetMapping(value = "/getall")
    public Result findByType(){
        //throw new BaseException(DictionaryEnum.NOT_FOUND);
      return Result.success(dictionaryService.selectAll());
//        Float a = null;
//        Float b = Float.intBitsToFloat(11);
//        System.out.println(a + b);
//        return null;
    }
}

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

能夠看到上訴相似的結果,個人項目啓動太麻煩了含SpringCloud 就不展現了。redis

Swagger2的註解

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

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