zoukankan      html  css  js  c++  java
  • 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我更喜欢这个,你呢

  • 相关阅读:
    中国大陆地区用户请特别注意:请勿存放违反当地法律法规文件
    JAVA日报
    JAVA日报
    JAVA日报
    JAVA日报
    JAVA日报
    JAVA日报
    JAVA日报
    JAVA日报
    JAVA日报
  • 原文地址:https://www.cnblogs.com/blackCatFish/p/14005589.html
Copyright © 2011-2022 走看看