Springboot 基於swagger 整合Knife4j


程序員在開發過程中討厭和不想做的就是寫接口文檔了吧(反正我是這么回事,寫文檔沒啥技術性浪費時間)后來得知了swagger 簡直是程序員的福音了吧! swagger官網

首先正常使用的一個東西肯定要引入依賴了

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

將上面的代碼塊引導自己項目中之后也別忘了配置

SwaggerConfig.class

package com.unionman.springbootsecurityauth2.config;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @program: blackCatFish
 * @description: Swagger配置類
 * @author: zly
 * @create: 2020-11-06 15:06
 **/
@EnableKnife4j
//開啟Swagger @EnableSwagger2 @Configuration
public class SwaggerConfig { /** * 創建API應用 * apiInfo() 增加API相關信息 * 通過select()函數返回一個ApiSelectorBuilder實例,用來控制哪些接口暴露給Swagger來展現, * 本例采用指定掃描的包路徑來定義指定要建立API的目錄。 */ @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select() .apis(RequestHandlerSelectors.basePackage("com.unionman.springbootsecurityauth2.controller")).paths(PathSelectors.any()).build(); } /** * 創建該API的基本信息(這些基本信息會展現在文檔頁面中) * 訪問地址:http://項目實際地址/swagger-ui.html */ private ApiInfo apiInfo() { return new ApiInfoBuilder().title("黑鯰魚Blog's").description("黑鯰魚博客文檔接口") .contact(new Contact("BlackCatFish", "", "")).version("1.0").build(); } }
apis(RequestHandlerSelectors.basePackage("com.unionman.springbootsecurityauth2.controller") 掃描這個包下面的所有controller

Swagger中常用的注解

序號 注解  用法
1 @Api  用於類准確的說是用於controller表示這個類是swagger資源
2 @ApiModel 用於實體類標識對類進行說明用於參數實體類接收
3 @ApiOperation  用於方法,標識一個http請求
4 @ApiModelPropertiy 用於方法字段,標識對於屬性的說明
5 @ApiParam 用於請求參數,標識請求參數的說明
6 @ApiIgnore() 用於類,方法,方法參數 
表示這個方法或者類被忽略 
7 @ApiImplicitParam() 用於方法 
表示單獨的請求參數 
8 @ApiImplicitParams() 用於方法,包含多個 @ApiImplicitParam

 

實體類代碼

@Getter
@Setter
@Entity
@Table(name = "um_t_user")
@ApiModel("用戶實體類")
public class User extends Base implements Serializable {
    private static final long serialVersionUID = -8478114427891717226L;

    /**
     * 用戶賬號
     */
    @ApiModelProperty("用戶賬號")
    @Length(max = 50,message = "用戶賬號不能超過50長度")
    private String account;

    /**
     * 用戶名
     */
    @ApiModelProperty("用戶賬號")
    @Length(max = 50,message = "用戶賬號不能超過50長度")
    private String name;

    /**
     * 用戶密碼
     */
    @ApiModelProperty("用戶密碼")
    @JsonIgnore
    private String password;

    /**

ps @Length是對字段的長度的限制,@JsonIgnore返回json格式數據可不返回這個字段

controller

package com.unionman.springbootsecurityauth2.controller;

import com.unionman.springbootsecurityauth2.dto.LoginUserDTO;
import com.unionman.springbootsecurityauth2.dto.UserDTO;
import com.unionman.springbootsecurityauth2.service.RoleService;
import com.unionman.springbootsecurityauth2.service.UserService;
import com.unionman.springbootsecurityauth2.utils.AssertUtils;
import com.unionman.springbootsecurityauth2.vo.ResponseVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @author zly
 * @description 用戶權限管理
 * @date 2019/4/19 13:58
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/auth/")
@Api(tags = "用戶權限管理")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RedisTokenStore redisTokenStore;

    /**
     * @param userDTO
     * @return
     * @description 添加用戶
     */
    @PostMapping("addUser")
    @ApiOperation("添加用戶")
    public ResponseVO add(@Valid @RequestBody UserDTO userDTO) throws Exception {
        userService.addUser(userDTO);
        return ResponseVO.success();
    }

    /**
     * @param id
     * @return
     * @description 刪除用戶
     */
    @DeleteMapping("deleteUser/{id}")
    @ApiOperation("刪除用戶")
    public ResponseVO deleteUser(@PathVariable("id") Integer id) throws Exception {
        userService.deleteUser(id);
        return ResponseVO.success();
    }

    /**
     * @param userDTO
     * @return
     * @descripiton 修改用戶
     */
    @PutMapping("updateUser")
    @ApiOperation("修改用戶")
    public ResponseVO updateUser(@Valid @RequestBody UserDTO userDTO) {
        userService.updateUser(userDTO);
        return ResponseVO.success();
    }

    /**
     * @return
     * @description 獲取用戶列表
     */
    @GetMapping("findAllUser")
    @ApiOperation("獲取用戶列表")
    public ResponseVO findAllUser() {
        return userService.findAllUserVO();
    }

    /**
     * @param loginUserDTO
     * @return
     * @description 用戶登錄
     */
    @PostMapping("user/login")
    public ResponseVO login(LoginUserDTO loginUserDTO) {
        return userService.login(loginUserDTO);
    }


    /**
     * @param authorization
     * @return
     * @description 用戶注銷
     */
    @GetMapping("user/logout")
    public ResponseVO logout(@RequestHeader("Authorization") String authorization) {
        redisTokenStore.removeAccessToken(AssertUtils.extracteToken(authorization));
        return ResponseVO.success();
    }

    /**
     * @return
     * @description 獲取所有角色列表
     */
    @GetMapping("findAllRole")
    @ApiOperation("獲取角色列表")
    public ResponseVO findAllRole() {
        return roleService.findAllRoleVO();
    }


}

啟動項目訪問://http:ip:prot/swagger-ui.html

如圖所示

 

 到這來似乎和我講的Knife4j沒有關系哦 久等了

老套路在依賴中添加

  <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <!--在引用時請在maven中央倉庫搜索最新版本號-->
            <version>2.0.4</version>
        </dependency>

在Swagger配置類中加上開啟knife4j的注解

@EnableKnife4j

 

 

 在訪問http:ip:prot/doc.html

如下圖

 

 點開某個接口

 

 對比swagger界面knife4j支持全文搜索接口,可以給接口添加一些請求頭,測試接口功能比swagger增強些比postman弱 q_q 界面更好看寫(個人視覺)

自從接觸到knife4j我更喜歡這個,你呢


免責聲明!

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



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