1. 程式人生 > >Springboot 學習之Swagger2整合

Springboot 學習之Swagger2整合

背景 在如今前後端分離的大背景下,前後端唯一打交道的就是API介面。前端只需要向後端請求url地址,後端只需將資料返回即可。前端工程師拿到的既是後端給到的一份完整的API文件,如果專案體量非常大的情況下,整理這些文件就需要浪費大量的時間。如果業務有變更的情況下,還需要再去更新文件,維護成本也是非常大。

今天介紹的主角就是Swagger線上生成API文件,極大的減少了人力的維護成本。可以線上直接在文件介面中測試。主要演示一下與Springboot整合的使用。Swagger支援多種語言的整合,詳細可以通過檢視其它資料。也支援文件的編寫, 文件編寫

整合步驟

引入依賴檔案

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

編寫配置檔案

package cc.mrbird.common.swagger;

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; /** * @Auther: jerry.feng * @Date: 2018/11/5 * @Description: Swagger2 配置 */ @Configuration public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() //api文件掃描的包 .apis(RequestHandlerSelectors.basePackage("cc.mrbird.system.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("CloudWallet API文件") .description("CloudWallet 雲錢包 RESTful介面文件") .termsOfServiceUrl("https://blog.csdn.net/fw19940314/article/list/") .version("1.0.1") .build(); } }

開啟Swagger 通過@EnableSwagger2 註解

@SpringBootApplication
@EnableTransactionManagement
@EnableCaching
@EnableSwagger2
@EnableAsync
public class Application {
    private static Logger log = LoggerFactory.getLogger(Application.class);
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        log.info("FEBS started up successfully at {} {}", LocalDate.now(), LocalTime.now());
    }
}

API(Controller)層的編寫只截取了部分,一個是帶引數,一個是無引數

@RestController
public class DeptController {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private DeptService deptService;

    @ApiOperation(value="獲取部門資訊", notes="獲取所有部門資訊")
    @RequestMapping(value = "dept/tree", method = RequestMethod.GET)
    @ResponseBody
    public ResponseBo getDeptTree() {
        try {
            Tree<Dept> tree = this.deptService.getDeptTree();
            return ResponseBo.ok(tree);
        } catch (Exception e) {
            log.error("獲取部門樹失敗", e);
            return ResponseBo.error("獲取部門樹失敗!");
        }
    }
    @ApiOperation(value="查詢部門資訊", notes="根據url的id來獲取部門詳細資訊")
    @ApiImplicitParam(name = "deptId", value = "部門ID", required = true, dataType = "Long")
    @RequestMapping(value = "dept/getDept", method = RequestMethod.GET)
    @ResponseBody
    public ResponseBo getDept(Long deptId) {
        try {
            Dept dept = this.deptService.findById(deptId);
            return ResponseBo.ok(dept);
        } catch (Exception e) {
            log.error("獲取部門資訊失敗", e);
            return ResponseBo.error("獲取部門資訊失敗,請聯絡網站管理員!");
        }
    }
}

註解的使用: swagger通過註解表明該介面會生成文件,包括介面名、請求方法、引數、返回資訊的等等。 @Api:修飾整個類,描述Controller的作用 @ApiOperation:描述一個類的一個方法,或者說一個介面 @ApiParam:單個引數描述 @ApiModel:用物件來接收引數 @ApiProperty:用物件接收引數時,描述物件的一個欄位 @ApiResponse:HTTP響應其中1個描述 @ApiResponses:HTTP響應整體描述 @ApiIgnore:使用該註解忽略這個API @ApiError :發生錯誤返回的資訊 @ApiImplicitParam:一個請求引數 @ApiImplicitParams:多個請求引數

啟動專案,訪問http://localhost:8080/swagger-ui.html#/

這裡是使用在真實的專案中,介面有很多,剛才建立的RESTful風格的dept-controller。 在這裡插入圖片描述

在這裡插入圖片描述

在這裡插入圖片描述

在這裡插入圖片描述

線上測試,即可獲取介面資料。

這裡需要說一點的是可能專案中使用了許可權框架,會攔截Swagger請求的資源,例如我這裡使用的shiro安全框架。需要講Swagger這部分資源設定為免登陸認證。

//在shiroFilterFactoryBean,filterChainDefinitionMap過濾器中放行這幾個請求即可。
        filterChainDefinitionMap.put("/swagger-ui.html", "anon");
        filterChainDefinitionMap.put("/webjars/**", "anon");
        filterChainDefinitionMap.put("/v2/**", "anon");
        filterChainDefinitionMap.put("/swagger-resources/**", "anon");

到這裡基本的開發API文件就生成成功

參考文章:https://blog.csdn.net/saytime/article/details/74937664