swagger2简单搭建
简介:
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。
API说明
@ApiModel定义模型
@ApiModel(description = "分页结果-传输对象")
public class PageResult implements Serializable {
@ApiModelProperty定义模型属性
@ApiModelProperty(value = "主键")
private Long id;
@Api定义控制器(广义接口)
@Api(tags = "品牌管理")
@RestController
@RequestMapping("/brand")
public class BrandController {
@ApiOperation定义方法
@ApiOperation(value = "查询所有品牌")
@GetMapping("/findAll")
public List<Brand> findAll() {
return brandRepo.findAll();
}
@ApiImplicitParams和@ApiImplicitParam定义参数
@ApiOperation(value = "根据主键删除")
@ApiImplicitParams(value = {
@ApiImplicitParam(name = "id", value = "主键", required = true, paramType = "float")
})
@GetMapping("/delete/{id}")
public Result delete(@PathVariable("id") Long id) {
1创建springboot项目
2修改pom.xml依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.22</version>
</dependency>
3修改application.yml文件
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
password: root
username: root
url: jdbc:mysql:///test?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
jpa:
show-sql: true
management:
endpoints:
web:
exposure:
include: health
4添加全局配置类
package com.lh.proj.swaggerdemo;
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@EnableSwagger2
@Configuration
public class AppSwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.select().apis(RequestHandlerSelectors.basePackage("com.lh.proj.swaggerdemo"))
.paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("七易众筹")
.description("图书模块")
.version("1.0.release").build();
}
}
5创建实体类
package com.lh.proj.swaggerdemo.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
@Entity
@Data
@Table(name = "tb_book")
@ApiModel(description = "实体类-图书")
public class TbBook {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@ApiModelProperty(value = "ID")
private Long id;
@ApiModelProperty(value = "书名")
private String name;
@ApiModelProperty(value = "价格")
private BigDecimal price;
@ApiModelProperty(value = "数量")
private int quantity;
@ApiModelProperty(value = "创建时间")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createDate;
@ApiModelProperty(value = "更新时间")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateDate;
}
6输出传输对象
package com.xxx.proj.swaggerdemo.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(description = "数据传输对象-分页结果")
public class PageResult {
@ApiModelProperty(value = "总条数")
Long total;
@ApiModelProperty(value = "结果集")
List rows;
}
package com.lh.proj.swaggerdemo.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
@ApiModel(description = "数据传输对象-通用结果集")
public class Result {
@ApiModelProperty(value = "操作结果")
private boolean success;
@ApiModelProperty(value = "操作消息")
private String message;
}
7控制层
package com.lh.proj.swaggerdemo.controller;
import com.lh.proj.swaggerdemo.dto.PageResult;
import com.lh.proj.swaggerdemo.dto.Result;
import com.lh.proj.swaggerdemo.entity.TbBook;
import com.lh.proj.swaggerdemo.repo.TbBookRepo;
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.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RequestMapping("/book")
@RestController
@Api(tags = "图书管理")
public class BookController {
@Autowired
private TbBookRepo tbBookRepo;
@GetMapping("/findAll")
@ApiOperation(value = "查询所有图书")
public List<TbBook> findAll() {
return tbBookRepo.findAll();
}
@PostMapping("/add")
@ApiOperation(value = "新增")
public Result add(TbBook tbBook) {
try {
tbBookRepo.save(tbBook);
return new Result(true, "add success");
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "failed");
}
}
@PostMapping("/update")
@ApiOperation(value = "修改")
public Result update(@RequestBody TbBook tbBook) {
try {
tbBookRepo.save(tbBook);
return new Result(true, "添加成功");
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "添加失败");
}
}
@GetMapping("/findPage/{currentPage}/{size}")
@ApiOperation(value = "分页查询")
@ApiImplicitParams({
@ApiImplicitParam(name = "currentPage", value = "当前页码", required = true, dataTypeClass = Integer.class),
@ApiImplicitParam(name = "size", value = "每页条数", required = true, dataTypeClass = Integer.class)
})
public PageResult findPage(@PathVariable("currentPage") int currentPage, @PathVariable("size") int size) {
Page<TbBook> page = tbBookRepo.findAll(PageRequest.of(currentPage, size));
return new PageResult(page.getTotalElements(), page.getContent());
}
@GetMapping("/findPage2")
@ApiOperation(value = "分页查询2")
@ApiImplicitParams({
@ApiImplicitParam(name = "currentPage", value = "当前页码", required = true, dataTypeClass = Integer.class),
@ApiImplicitParam(name = "size", value = "每页条数", required = true, dataTypeClass = Integer.class)
})
public PageResult findPage2(@RequestParam("currentPage") int currentPage, @RequestParam("size") int size) {
Page<TbBook> page = tbBookRepo.findAll(PageRequest.of(currentPage, size));
return new PageResult(page.getTotalElements(), page.getContent());
}
@GetMapping("/findOne")
@ApiOperation(value = "根据id查询")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "ID", required = true, dataTypeClass = Long.class)
})
public TbBook findOne(Long id) {
return tbBookRepo.findById(id).get();
}
@GetMapping("/delete")
@ApiOperation(value = "删除")
@ApiImplicitParams({
@ApiImplicitParam(name = "ids", value = "ID集合", required = true, dataTypeClass = Long.class)
})
public Result delete(Long[] ids) {
try {
for (Long id : ids) {
tbBookRepo.deleteById(id);
}
return new Result(true, "删除成功");
} catch (Exception e) {
e.printStackTrace();
return new Result(false, "删除失败");
}
}
}
8运行访问
http://localhost:8080/swagger-ui.html
结果