Knife4j框架

1.Knife4j是一款基于Swagger 2的在线API文档框架

在Spring Boot中,使用此框架的时候,需要

  • 添加依赖
  • <!-- Knife4j Spring Boot:在线API -->
    <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>knife4j-spring-boot-starter</artifactId>
        <version>2.0.9</version>
    </dependency>
  • 在配置文件(application.properties) 中开启增强模式
  • # 开启Knife4j的增强模式
    knife4j.enable=true
  • 关于配置类,在项目根包下创建config.Knife4jConfiguration,代码如下
  • 需要注意basePackage属性的值 
  • package cn.tedu.csmall.product.config;
    
    import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    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.EnableSwagger2WebMvc;
    
    /**
     * Knife4j配置类
     *
     * @author java@tedu.cn
     * @version 0.0.1
     */
    @Slf4j
    @Configuration
    @EnableSwagger2WebMvc
    public class Knife4jConfiguration {
    
        /**
         * 【重要】指定Controller包路径
         */
        private String basePackage = "cn.tedu.csmall.product.controller";
        /**
         * 分组名称
         */
        private String groupName = "product";
        /**
         * 主机名
         */
        private String host = "http://java.tedu.cn";
        /**
         * 标题
         */
        private String title = "酷鲨商城在线API文档--商品管理";
        /**
         * 简介
         */
        private String description = "酷鲨商城在线API文档--商品管理";
        /**
         * 服务条款URL
         */
        private String termsOfServiceUrl = "http://www.apache.org/licenses/LICENSE-2.0";
        /**
         * 联系人
         */
        private String contactName = "Java教学研发部";
        /**
         * 联系网址
         */
        private String contactUrl = "http://java.tedu.cn";
        /**
         * 联系邮箱
         */
        private String contactEmail = "java@tedu.cn";
        /**
         * 版本号
         */
        private String version = "1.0.0";
    
        @Autowired
        private OpenApiExtensionResolver openApiExtensionResolver;
    
        public Knife4jConfiguration() {
            log.debug("加载配置类:Knife4jConfiguration");
        }
    
        @Bean
        public Docket docket() {
            String groupName = "1.0.0";
            Docket docket = new Docket(DocumentationType.SWAGGER_2)
                    .host(host)
                    .apiInfo(apiInfo())
                    .groupName(groupName)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage(basePackage))
                    .paths(PathSelectors.any())
                    .build()
                    .extensions(openApiExtensionResolver.buildExtensions(groupName));
            return docket;
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title(title)
                    .description(description)
                    .termsOfServiceUrl(termsOfServiceUrl)
                    .contact(new Contact(contactName, contactUrl, contactEmail))
                    .version(version)
                    .build();
        }
    
    }

    需要注意的是,以上代码仅适用于Spring Boot 2.6以下(不含2.6)版本

完成后,重启,打开浏览器,通过访问本地地址后加/doc.html即可访问Knife4j的Api文档,包括

  • @Api:添加在控制类上,配置其tags属性,用于指定模块名称,在指定的模块名称,可以使用数字编号作为名称的前缀,则多个管理模块将按照编号顺序来显示,例如
    • @RestController
      @RequestMapping("/albums")
      @Api(tags = "03. 相册管理模块")
      public class AlbumController {
      
          @GetMapping("/test")
          public void test() {}
      
      }
  • @ApiOperation:添加在控制器类中处理请求的方法上,配置其value属性,用于指定业务接口名称,例如
    • @ApiOperation("删除品牌")
      @PostMapping("/delete")
      public String delete(Long id) {
      }
  • @ApiOperationSupport:添加在控制器类中处理请求的方法上,配置器order属性,用于指定业务接口的排序序号,最终,同一个模块中的多个业务接口将按此编号升序排列,例如:
    • @ApiOperation("删除品牌")
      @ApiOperationSupport(order = 200)
      @PostMapping("/delete")
      public String delete(Long id) {
      }
  •  @ApiModelProperty:添加在POJO类属性上,配置其value属性,用于指定请求参数的名称(说明),配置其required属性,用于指定“是否必须提交此请求参数”(仅用于显示,不具备检查功能),配置其example属性,用于指定''示例“;
    • @Data
      public class BrandAddNewDTO implements Serializable {
      
          /**
           * 是否启用,1=启用,0=未启用
           */
          @ApiModelProperty(value = "是否启用,1=启用,0=未启用", example = "1", required = true)
          private Integer enable;
      
      }
  • @ApiImplcitParam:添加在控制器类中处理请求的方法,配置其name属性,指定方法的参数的变量名,配置其value属性,指定此参数的说明,配置其required属性,指定此参数”是否必须先提交“,配置其dataType属性,指定此参数的数据类型,例如:
    • @ApiOperation("删除品牌")
      @ApiOperationSupport(order = 200)
      @ApiImplicitParam(name = "id", value = "品牌id", required = true, dataType = "long")
      @PostMapping("/delete")
      public String delete(Long id) {
      }
  •  @ApiImplictParams:添加在控制器类中处理请求的方法,当有多个参数需要配置时,使用此注解,且此注解的值是@ApiImlicirParm的数组,例如
    • @ApiOperation("删除品牌")
      @ApiOperationSupport(order = 200)
      @ApiImplicitParams({
          @ApiImplicitParam(name = "id", value = "品牌id", 
                            required = true, dataType = "long")
      })
      @PostMapping("/delete")
      public String delete(Long id) {
      }
  • @ApiIgnore:添加在处理请求的方法的参数上,当某个参数不需要显示在API文档中,则需要在参数上添加此注解,例如HttpServletRequestHttpSession等,例如:
    • @ApiOperation("删除品牌")
      @ApiOperationSupport(order = 200)
      @ApiImplicitParam(name = "id", value = "品牌id", required = true, dataType = "long")
      @PostMapping("/delete")
      public String delete(Long id, @ApiIgnore HttpSession session) {
      }

2.Spring MVC与RESTful

在 Spring MVC框架中,接收请求的参数做法有:

  • 将各请求参数声明为处理请求的方法的参数
  • 将各请求参数封装到自定义的POJO类型中,并使用POJO类型作为处理请求的方法的参数
  • 在配置请求路径时使用占位符,并通过@PathVariable注解来接收请求参数的值

RESTful是一种设计软件的风格,其典型特征包括:将具有“唯一性”的请求参数值作为URL的一部分,例如:CSDN就是这种样式

Spring MVC框架很好的支持了RESTful,在使用@RequestMapping系列注解配置请求路径时。可以使用{名称}作为占位符来接收请求,例如:
 

@PostMapping("/{id}/delete")

则以上路径中的{id}可以是任何值,均能匹配到以上路径!

在处理请求的方法上,仍使用Long id来接收URL中的占位符对应的值,并且,此参数需要添加@PathVariable注解,例如

@PostMapping("/{id}/xxxxxx")
public String xxxxxx(@PathVariable Long id){
}

在使用@PathVariable注解时,如果请求参数的名称与占位符不一致时,可以用过注解参数进行配置,例如:
 

@PostMapping("/{id}/xxxxxx")
public String xxxxxx(@PathVariable("id") Long id){
}

另外在{}占位符中,可以在自定义名称的右侧添加冒号(:),并在冒号的右侧添加正则表达式,以现实按需匹配,例如
 

@PostMapping("/{id:[0-9]+}/xxxxxx")
public String xxxxxx(@PathVariable Long id){
}

在同一个项目中,多个使用了占位符,且正则表达式不冲突得URL,是允许共存得!例如:


@PostMapping("/{id:[0-9]+}/xxxxxx")
public String xxxxxx(@PathVariable Long id) {
}

@PostMapping("/{id:[a-zA-Z]+}/xxxxxx")
public String xxxxxx(@PathVariable String id) {
}

在RESTful的设计风格中,如果没有更好的选择,在设计URL时,可以:

/数据类型的复数:表示获取某类型的数据的列表
例如:/brands表示获取品牌列表
/数据类型的复数/{id}:表示获取某类型的id=?的数据
例如:/brands/{id},实际请求路径可能是/brands/1,则表示获取id=1的品牌数据
/数据类型的复数/{id}/命令:表示针对某类型的id=?的数据进行某操作
例如:/brands/{id}/delete,实际请求路径可能是/brands/1/delete,则表示删除id=1的品牌数据
/数据类型的复数/{id}/属性/命令:表示针对某类型的id=?的数据的某属性进行某操作
其它
另外,RESTful思想建议针对不同的需求,使用不同的请求方式,如下:

GET:获取数据
POST:增加数据
PUT:修改数据
DELETE:删除数据

3.关于响应结果

控制器处理完请求后,向客户端进行响应时,推荐使用JSON格式的响应数据,并且,此JSON格式的数据中至少应该包括:

  • 业务状态码
  • 提示信息

在Spring MVC框架中,当需要向客户端响应JSON格式的结果时,需要:

  • 当前处理请求的方法必须是“响应正文”的
    • 在处理请求的方法或控制器类上使用@ResponseBody,或控制器类上使用@RestController,就是响应正文的
  • 在项目中添加jackson-databind的依赖
    • 包含在spring-boot-starter-web依赖项中
  • 开启注解驱动
    • 使用注解模式的Spring MVC项目(包括Spring Boot)均默认开启
  • 使用自定义的类型作为处理请求的方法的返回值类型,并且,此类中应该包含响应的JSON中的各属性

则在项目的根包下创建web.JsonResult类·

package cn.tedu.csmall.product.web;

import cn.tedu.csmall.product.ex.ServiceCode;
import cn.tedu.csmall.product.ex.ServiceException;
import lombok.Data;
import java.io.Serializable;

@Data
public class JsonResult<T> implements Serializable {

    /**
     * 业务状态码
     */
    private Integer state;
    /**
     * 错误时的提示消息
     */
    private String message;
    /**
     * 成功时响应的数据
     */
    private T data;

    public JsonResult() {
    }

    private JsonResult(Integer state, String message, T data) {
        this.state = state;
        this.message = message;
        this.data = data;
    }

    public static JsonResult<Void> ok() {
        return ok(null);
    }

    public static <T> JsonResult<T> ok(T data) {
        return new JsonResult(ServiceCode.OK.getValue(), null, data);
    }

    public static JsonResult<Void> fail(ServiceException e) {
        return fail(e.getServiceCode().getValue(), e.getMessage());
    }

    public static JsonResult<Void> fail(Integer state, String message) {
        return new JsonResult(state, message, null);
    }

}

4.关于处理异常

在java语言中,异常的体系结构大致是:

Throwable
-- Error
-- -- OutOfMemoryError(OOM)
-- Exception
-- -- IOException
-- -- RuntimeException
-- -- -- NullPointerException(NPE)
-- -- -- ClassCastException
-- -- -- IndexOutOfBoundsException
-- -- -- -- ArrayIndexOutOfBoundsException
-- -- -- -- StringIndexOutOfBoundsException

如果调用的方法抛出了非“RuntimeException”,则必须:

  • 当前方法声明抛出此异常
  • 使用try···catch代码块包裹此方法的调整代码
    • 真正意义上的“处理了异常”

关于"处理异常",需要明确的告诉用户“这次操作失败了,失败的原因是xxxxxxxx,你可以通过xxxxx再次尝试”并避免出现此类错误!

所以在整个项目中,只有Controller才是适合且必须处理异常的组件,因为它可以将错误的描述文本响应到客户端去,而项目中的其他组件(例如Service等)不适合且不应该处理异常,因为它们不可以直接与客户端进行交互,且如果他们处理了异常,则Controller在调用时将无法知道曾经出现过异常,更加无法处理!; 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

牛老师来巡山~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值