Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务的接口文档 . 接口: controller相应的路径方法
目前的项目基本都是前后端分离,后端为前端提供接口的同时,还需同时提供接口的说明文档。但我们的代码总是会根据实际情况来实时更新,这个时候有可能会忘记更新接口的说明文档,造成一些不必要的问题。
<!--swagger2依赖-->
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.7.8</version>
</dependency>
@Configuration
@EnableSwagger2 //开启swagger注解驱动
public class SwaggerConfig {
@Bean //把方法返回的数据对象 交于spring容器管理
public Docket docket(){
Docket docket = new Docket(DocumentationType.SWAGGER_2).groupName("QY163")
.apiInfo(getInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.ykq.controller")) //只为com.ykq.controller包下的类生成接口文档
.build();
return docket;
}
private ApiInfo getInfo(){
Contact DEFAULT_CONTACT = new Contact("王永亮", "http://www.baidu.com", "[email protected]");
ApiInfo apiInfo=new ApiInfo("QY163心里测试系统API", "QY163心里测试系统API", "1.1.0", "http://www.jd.com",
DEFAULT_CONTACT, "志远科技", "http://www.aaa.com", new ArrayList<VendorExtension>());
return apiInfo;
}
}
http://ip:port/swagger-ui.html路径
使用swagger注解对接口参数加以说明。
@Api(tags=“”)====使用在controller类上
@ApiOperation(value=“”)====接口方法上 接口方法加以说明
@ApiParam(value = “”,name = “”,required = true)
@ApiModel====实体类
@ApiModelProperty===>实体类的属性说明
https://www.pppet.net/
定时器: 在指定的时间执行相应的业务代码。 应用场景: 比如: 定时删除OSS中冗余的文件 三十分钟未支付---->取消订单。
定时发送短信---->11.11====>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
@Component //交于spring容器该类对象
public class QuarzConfig {
@Autowired
private EmpMapper empMapper;
@Scheduled(cron = "0/5 * * * * ? ")
public void show(){
//1.查询过期的订单
List<Emp> emps = empMapper.selectList(null);
System.out.println(emps);
//2.删除过期的订单
}
}
@SpringBootApplication
@MapperScan(basePackages = "com.ykq.dao")
@EnableScheduling //开启定时器注解
public class Qy163Springboot03Application {
public static void main(String[] args) {
SpringApplication.run(Qy163Springboot03Application.class, args);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.12.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.lmy</groupId>
<artifactId>springBoot4</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springBoot4</name>
<description>springBoot4</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.7.8</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql:///homework1
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
mybatis-plus.mapper-locations=classpath:/mapper/**/*.xml
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@MapperScan(basePackages = "com.lmy.mapper")
@EnableSwagger2
public class SpringBoot4Application {
public static void main(String[] args) {
SpringApplication.run(SpringBoot4Application.class, args);
}
}
package com.lmy.pojo.entry;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.format.annotation.DateTimeFormat;
/**
*
* @TableName student
*/
//@TableName(value ="student")
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@ApiModel(value = "学生实体类")
public class Student implements Serializable {
/**
*
*/
@TableId(type = IdType.AUTO)
@ApiModelProperty(value = "学生id")
private Integer studentno;
/**
*
*/
@ApiModelProperty(value = "班级id")
private Integer gradeid;
/**
*
*/
@ApiModelProperty(value = "姓名")
private String name;
/**
*
*/
@ApiModelProperty(value = "性别")
private String sex;
/**
*
*/
@ApiModelProperty(value = "年龄")
private Integer age;
/**
*
*/
@ApiModelProperty(value = "城市")
private String city;
/**
*
*/
@ApiModelProperty(value = "电话号码")
private Integer phone;
@ApiModelProperty(value = "生日")
@JsonFormat(timezone="GMT%2B8", pattern="yyyy-MM-dd")
// @DateTimeFormat(pattern="yyyy-MM-dd")//接收参数的格式化
private Date birthday;
@TableField(exist = false)
private Grade grade;
}
package com.lmy.pojo.entry;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
*
* @TableName grade
*/
//@TableName(value ="grade")
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Grade implements Serializable {
/**
* 班级id
*/
@TableId
private Integer gradeid;
/**
* 班级名字
*/
private String gradename;
}
package com.lmy.pojo.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@ApiModel(value = "接收学生的请求参数")
public class StudentVo {
@ApiModelProperty(value = "学生姓名")
private String name;
@ApiModelProperty(value = "开始时间")
@JsonFormat(timezone="GMT%2B8", pattern="yyyy-MM-dd")
///@DateTimeFormat(pattern="yyyy-MM-dd")//接收参数的格式化
private Date startTime;
@ApiModelProperty(value = "结束时间")
@JsonFormat( timezone="GMT%2B8", pattern="yyyy-MM-dd")
//@DateTimeFormat(pattern="yyyy-MM-dd")//接收参数的格式化
private Date endTime;
}
package com.lmy.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration // 一定不要忽略此注解
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 所有接口
.allowCredentials(true) // 是否发送 Cookie
.allowedOrigins("*") //支持那些域跨域
//.allowedOriginPatterns("*") // 支持域
.allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"}) // 支持方法
.allowedHeaders("*")
.exposedHeaders("*");
}
}
package com.lmy.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
package com.lmy.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.VendorExtension;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
@Configuration
@EnableSwagger2 //开启swagger注解驱动
public class SwaggerConfig {
@Bean //把方法返回的数据对象 交于spring容器管理
public Docket docket(){
Docket docket = new Docket(DocumentationType.SWAGGER_2).groupName("QY163")
.apiInfo(getInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.lmy.controller")) //只为com.ykq.controller包下的类生成接口文档
.build();
return docket;
}
private ApiInfo getInfo(){
Contact DEFAULT_CONTACT = new Contact("李梦瑶", "http://www.baidu.com", "[email protected]");
ApiInfo apiInfo=new ApiInfo("QY163班心理测试系统API", "QY163班心理测试系统API", "1.1.0", "http://www.jd.com",
DEFAULT_CONTACT, "熊熊科技", "http://www.aaa.com", new ArrayList<VendorExtension>());
return apiInfo;
}
}
package com.lmy.util;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "公共json对象")
public class Result {
@ApiModelProperty(value = "状态码 200正常 500错误")
private Integer code;
@ApiModelProperty(value = "消息内容")
private String msg;
@ApiModelProperty(value = "数据")
private Object data;
}
package com.lmy.mapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lmy.pojo.entry.Student;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
public interface StudentMapper extends BaseMapper<Student> {
IPage<Student> findPage(IPage<Student> iPage, @Param("ew") Wrapper<Student> wrapper);
}
package com.lmy.mapper;
import com.lmy.pojo.entry.Grade;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface GradeMapper extends BaseMapper<Grade> {
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lmy.mapper.StudentMapper">
<resultMap id="BaseResultMap" type="com.lmy.pojo.entry.Student">
<id property="studentno" column="studentno" jdbcType="INTEGER"/>
<result property="gradeid" column="gradeid" jdbcType="INTEGER"/>
<result property="name" column="name" jdbcType="VARCHAR"/>
<result property="sex" column="sex" jdbcType="CHAR"/>
<result property="age" column="age" jdbcType="INTEGER"/>
<result property="city" column="city" jdbcType="VARCHAR"/>
<result property="phone" column="phone" jdbcType="INTEGER"/>
<result property="birthday" column="birthday" jdbcType="VARCHAR"/>
<association property="grade" javaType="com.lmy.pojo.entry.Grade" autoMapping="true">
<id property="gradeid" column="gradeid" jdbcType="INTEGER"/>
<result property="gradename" column="gradename" jdbcType="VARCHAR"/>
</association>
</resultMap>
<sql id="Base_Column_List">
studentno,s.gradeid,name,
sex,age,city,
phone,birthday,g.gradeid,g.gradename
</sql>
<!--查询所有学生信息-->
<select id="findPage" resultMap="BaseResultMap">
select <include refid="Base_Column_List"/> from student s join grade g on s.gradeid=g.gradeid
<if test="ew != null and ew.sqlSegment != ''">
and ${ew.sqlSegment}
</if>
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lmy.mapper.GradeMapper">
<resultMap id="BaseResultMap" type="com.lmy.pojo.entry.Grade">
<id property="gradeid" column="gradeid" jdbcType="INTEGER"/>
<result property="gradename" column="gradename" jdbcType="VARCHAR"/>
</resultMap>
<sql id="Base_Column_List">
gradeid,gradename
</sql>
</mapper>
package com.lmy.service;
import com.lmy.pojo.entry.Student;
import com.lmy.pojo.vo.StudentVo;
import com.lmy.util.Result;
import java.util.List;
public interface StudentService{
//vo:view Object 接受前端请求的数据对象
public Result findPage(Integer current, Integer pageSize, StudentVo studentVo);
Result batchDelete(List<Student> students);
}
package com.lmy.service.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lmy.pojo.entry.Student;
import com.lmy.pojo.vo.StudentVo;
import com.lmy.mapper.StudentMapper;
import com.lmy.service.StudentService;
import com.lmy.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* @author TR
* @description 针对表【student】的数据库操作Service实现
* @createDate 2023-04-12 19:27:46
*/
@Service
public class StudentServiceImpl implements StudentService {
@Autowired StudentMapper studentMapper;
@Override
public Result findPage(Integer current, Integer pageSize, StudentVo studentVo) {
//分页对象
Page<Student> page = new Page<>(current,pageSize);
//条件对象--xml
QueryWrapper<Student> wrapper = new QueryWrapper<>();
//判断是否为空
if (StringUtils.hasText(studentVo.getName())){
wrapper.like("name",studentVo.getName());
}
if (Objects.nonNull(studentVo.getStartTime())){
wrapper.ge("birthday",studentVo.getStartTime());
}
if (Objects.nonNull(studentVo.getEndTime())){
wrapper.le("birthday",studentVo.getEndTime());
}
IPage<Student> page1 = studentMapper.findPage(page, wrapper);
//公共对象---封装到Page对象中---
return new Result(200,"分页条件查询--学生信息--成功",page1);
}
@Override
public Result batchDelete(List<Student> students) {
List<Integer> collect = students.stream().map(item -> item.getStudentno()).collect(Collectors.toList());
int i = studentMapper.deleteBatchIds(collect);
if (i > 0) {
return new Result(200, "批量删除数据成功",null);
} else {
return new Result(500, "批量删除数据失败",null);
}
}
}
package com.lmy.service;
import com.lmy.util.Result;
public interface GradeService{
//查询所有部门
Result findAll();
}
package com.lmy.service.impl;
import com.lmy.pojo.entry.Grade;
import com.lmy.service.GradeService;
import com.lmy.mapper.GradeMapper;
import com.lmy.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author TR
* @description 针对表【grade】的数据库操作Service实现
* @createDate 2023-04-12 19:30:52
*/
@Service
public class GradeServiceImpl implements GradeService{
@Autowired
private GradeMapper gradeMapper;
@Override
public Result findAll() {
List<Grade> grades = gradeMapper.selectList(null);
return new Result(200,"查询部门成功",grades);
}
}
package com.lmy.controller;
import com.lmy.mapper.StudentMapper;
import com.lmy.pojo.entry.Student;
import com.lmy.pojo.vo.StudentVo;
import com.lmy.service.StudentService;
import com.lmy.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
//解决跨域问题
@RestController
@RequestMapping("student")
@Api(tags = "学生表操作API")
//@CrossOrigin
public class StudentController {
@Autowired
private StudentService studentService;
@Autowired
private StudentMapper studentMapper;
@PostMapping("findPage/{current}/{pageSize}")
@ApiOperation(value = "根据条件分页查询学生信息")
public Result findPage(
@ApiParam(value = "当前页面",name ="current",required = true,defaultValue = "1")
@PathVariable Integer current,
@ApiParam(value = "每页条数",name ="pageSize",required = true,defaultValue = "5")
@PathVariable Integer pageSize,
@RequestBody StudentVo studentVo
){
return this.studentService.findPage(current,pageSize,studentVo);
}
@GetMapping ("findById/{studentno}")
@ApiOperation(value = "根据id查询学生信息")
public Result findById(@PathVariable Integer studentno) {
return new Result(200, "查询学生信息成功", this.studentMapper.selectById(studentno));
}
@PostMapping("save")
@ApiOperation(value = "添加学生信息")
public Result insert(@RequestBody Student student){
Student student1 = new Student();
//student1.setStudentno(student.getStudentno());
student1.setGradeid(student.getGradeid());
student1.setName(student.getName());
student1.setSex(student.getSex());
student1.setAge(student.getAge());
student1.setCity(student.getCity());
student1.setPhone(student.getPhone());
student1.setBirthday(student.getBirthday());
return new Result(200, "添加学生信息成功",studentMapper.insert(student1));
}
@DeleteMapping("delete/{studentno}")
@ApiOperation(value = "根据id删除学生信息")
public Result deleteById(@PathVariable Integer studentno){
return new Result(200, "删除学生信息成功",studentMapper.deleteById(studentno));
/*List ids = new ArrayList<>();
ids.add(2);
ids.add(3);
ids.add(5);
int i = studentMapper.deleteBatchIds(ids);*/
}
//post和put请求可以传递json数据外 其他都不可以传递json数据
@PostMapping("batchdelete")
public Result batchdelete(@RequestBody List<Student> students){
return studentService.batchDelete(students);
}
@PutMapping ("update")
@ApiOperation(value = "修改学生信息")
public Result update(@RequestBody Student student){
Student student2 = new Student();
student2.setStudentno(student.getStudentno());
student2.setGradeid(student.getGradeid());
student2.setName(student.getName());
student2.setSex(student.getSex());
student2.setAge(student.getAge());
student2.setCity(student.getCity());
student2.setPhone(student.getPhone());
student2.setBirthday(student.getBirthday());
return new Result(200, "修改学生信息成功",studentMapper.updateById(student2));
}
}
package com.lmy.controller;
import com.lmy.service.GradeService;
import com.lmy.util.Result;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/grade")
public class GradeController {
@Autowired private GradeService gradeService;
@GetMapping("/list")
public Result list(){
return gradeService.findAll();
}
}