SpringBoot整合篇—knife4

一:引入maven依赖

		<dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>2.0.2</version>
        </dependency

第二步编写Config


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

/**
 * Swagger的配置类
 */
@Configuration
@EnableSwagger2
public class MyKnife4jConfiguration {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //为当前包路径,控制器类包
                .apis(RequestHandlerSelectors.basePackage("com.rj9.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    //构建 api文档的详细信息函数,注意这里的注解引用的是哪个
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //页面标题
                .title("Spring Boot 集成 knife4 测试接口文档")
                //创建人
                .contact(new Contact("嗨嗨嗨!", "http://www.baidu.com", "@qq.com"))
                //版本号
                .version("1.0")
                //描述
                .description("API 描述")
                .build();
    }
}


第三步编写实体类 这里使用伪造表数据 并没有使用数据库

package com.rj9.entity;

import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * 实体类
 */
@NoArgsConstructor// 生成无参的构造方法
@AllArgsConstructor// 生成满参的构造方法
@Accessors(chain = true)// 使用链式调用
@Data// 自动生成get/set方法、重写toString方法等方法
public class Student implements Serializable {


    @ApiModelProperty(value = "学生id")// 对属性进行简要说明
    private Integer studentId;

    @ApiModelProperty(value = "学生姓名")
    private String studentName;

    @ApiModelProperty(value = "学生分数")
    private Double studentScore;

}


第四步 编写service层

package com.rj9.service;

import com.rj9.entity.Student;
import com.rj9.vo.ResponseVo;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Service
 */
@Service
public class StudnetService {
    // 这里我们不使用数据库, 使用Map集合来模拟数据库中的表
    private static Map<Integer, Student> studentMap=new HashMap<>();
    private static Integer studentId=10001;
    static {
        studentMap.put(studentId, new Student(studentId, "张三", 92.5));
        studentId++;
        studentMap.put(studentId, new Student(studentId, "王五", 95.0));
        studentId++;
        studentMap.put(studentId, new Student(studentId, "李四", 66.5));
        studentId++;
    }

    /**
     * 插入一名学生返回影响行数
     * @param student
     * @return
     */
    public ResponseVo<Integer> addOneStudent(Student student){
        student.setStudentId(studentId);
        studentMap.put(studentId, student);
        studentId++;
        return new ResponseVo<>("插入一条数据成功", 200, 1);
    }

    /**
     * 删除一位学生返回影响行数
     * @param studentId
     * @return
     */
    public  ResponseVo<Integer> deleteOneStudentByStudentId(Integer studentId){
        if(studentMap.containsKey(studentId) == false){
            return new ResponseVo<>("您输入的id不存在", 200, 0);
        }
        studentMap.remove(studentId);
        return new ResponseVo<>("删除成功", 200, 1);
    }

    /**
     * 修改一位学生返回影响行数
     * @param student
     * @return
     */
    public ResponseVo<Integer> updateOneStudent(Student student){
        if(studentMap.containsKey(student.getStudentId()) == false){
            return new ResponseVo<>("根据学生id,您所修改的学生不存在", 200, 0);
        }
        studentMap.put(student.getStudentId(), student);
        return new ResponseVo<>("学生修改成功", 200, 1);
    }

    /**
     * 输入studentId查询并返回对应的学生
     * @param studentId
     * @return
     */
    public ResponseVo<Student> getOneStudentByStudentId(Integer studentId){
        if(studentMap.containsKey(studentId) == false){
            return new ResponseVo<>("您所查询的学生不存在", 200, null);
        }
        return new ResponseVo<>("查询成功", 200, studentMap.get(studentId));
    }

    /**
     * 获取所有学生
     * @return
     */
    public ResponseVo<Collection<Student>> getAllStudent(){
        return new ResponseVo<>("获取全部学生成功", 200, studentMap.values());
    }
}

第五步 编写Controller层

package com.rj9.controller;

import com.rj9.entity.Student;
import com.rj9.service.StudnetService;
import com.rj9.vo.ResponseVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;


/**
 * Controller
 */
@Api("学生管理相关接口")
@RestController //@Controller + @ResponseBody
@RequestMapping("/student")
public class StudenController {
    @Autowired
    private StudnetService studentService;

    /**
     * 添加一名学生
     * @param student
     * @return
     */
    @ApiOperation("添加一名学生")// 为每个handler添加方法功能描述
    @PostMapping("/add_student.action")
    @ApiImplicitParam(name = "student", value = "所添加的学生", dataTypeClass = Student.class)
    public ResponseVo<Integer> addOneStudent(Student student) {
        return studentService.addOneStudent(student);
    }

    /**
     * 根据studentId删除一名学生
     * @param studentId
     * @return
     */
    @ApiOperation("根据studentId删除一名学生")
    @DeleteMapping("/delete_student/{studentId}.action")
    public ResponseVo<Integer> deleteOneStudentByStudentId(@PathVariable Integer studentId) {
        return studentService.deleteOneStudentByStudentId(studentId);
    }

    /**
     * 修改一名学生
     * @param student
     * @return
     */
    @ApiOperation("修改一名学生")
    @PutMapping("/update_student.action")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentId", value = "学号", required = true), //required为是否必填项
            @ApiImplicitParam(name = "studentName", value = "学生姓名", required = false),
            @ApiImplicitParam(name = "studentSex", value = "学生性别", required = false),
            @ApiImplicitParam(name = "studentScore", value = "学生分数", required = false)
    })
    public ResponseVo<Integer> updateOneStudent(Student student) {
        return studentService.updateOneStudent(student);
    }

    /**
     * 根据id获取一名学生
     * @param studentId
     * @return
     */
    @ApiOperation("根据id获取一名学生")
    @GetMapping("/get_ont_student/{studentId}.action")
    public ResponseVo<Student> getOntStudentByStudentId(@PathVariable Integer studentId) {
        return studentService.getOneStudentByStudentId(studentId);
    }

    /**
     * 获取全部学生
     * @return
     */
    @ApiOperation("获取全部学生")
    @GetMapping("/get_all_student.action")
    public ResponseVo<Collection<Student>> getAllStudent() {
        return studentService.getAllStudent();
    }
}


第六步 编写配置文件(因为没有使用数据库就只配置了Tomcat)

# Tomcat
server:
  tomcat:
    uri-encoding: UTF-8
    max-threads: 1000
    min-spare-threads: 30
  port: 8200
  servlet:
    context-path: /

第七步 访问

http://127.0.0.1:8200/doc.html#/home

如图
在这里插入图片描述

注意事项:
如果你的SpringBoot版本高于2.6 及以上 在配置文件中加上这个

spring:
  mvc:
    pathmatch:
      # Springfox使用的路径匹配是基于AntPathMatcher的,而Spring Boot 2.6.X使用的是PathPatternMatcher
      # 所以需要配置此参数
      matching-strategy: ant_path_matcher

原因是:

在SpringBoot2.6.0以后的版本中将SpringMVC 默认路径匹配策略从AntPathMatcher 更改为PathPatternParser,导致出错!(低版本swagger和knife4不兼容高版本的SpringBoot)

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值