博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
swagger2简单搭建
阅读量:3949 次
发布时间:2019-05-24

本文共 8332 字,大约阅读时间需要 27 分钟。

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
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依赖

io.springfox
springfox-swagger-ui
2.9.2
io.springfox
springfox-swagger2
2.9.2
io.swagger
swagger-models
io.swagger
swagger-models
1.5.22

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: truemanagement:  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@Configurationpublic 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
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
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
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
结果
在这里插入图片描述

转载地址:http://qqrwi.baihongyu.com/

你可能感兴趣的文章
Custom Drawing 自定义绘制
查看>>
跨平台的文字编码转换方法--ICU
查看>>
ICU4C 4.4 静态库的编译
查看>>
FTP下载类, windows平台下对CFtpConnection上传下载的封装类
查看>>
代码自动生成-宏带来的奇技淫巧
查看>>
VC com开发中实现IObjectSafety
查看>>
c# 正则表达式基础
查看>>
C#3.0语言新特性
查看>>
W32Dasm反汇编工具使用教程
查看>>
EXE破解工具介绍
查看>>
机械码对应值
查看>>
常用语音编码的WAVE文件头格式剖析--各种编码
查看>>
有关数据挖掘的10个常见问题
查看>>
电信数据挖掘之流失管理
查看>>
web DB优化思路
查看>>
敏捷笔记
查看>>
SOA业务理解与应用
查看>>
Google File System(中文翻译)
查看>>
Google's BigTable 原理 (翻译)
查看>>
MapReduce:超大机群上的简单数据处理
查看>>