前后端联调神器swagger以及美观化

介绍

  swagger 是一款开源的接口管理技术, 他可以让我们的接口可视化,调试,参数说明,在前后端联调中是不可缺少的开发利器。

优势

支持 API 自动生成同步的在线文档:使用 Swagger 后可以直接通过代码生成文档,不再需要自己手动编写接口
文档了,对程序员来说非常方便,可以节约写文档的时间去学习新技术。
提供 Web 页面在线测试 API:光有文档还不够,Swagger 生成的文档还支持在线测试。参数和格式都定好了,直接
在界面上输入参数对应的值即可在线测试接口。

怎么做

引入maven依赖

        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>${io.swagger.version}</version>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
            <version>${io.swagger.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger2.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger2.version}</version>
        </dependency>
        <!--这个依赖并非是swagger的 这个是让我们的swagger页面更美观-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>${knife4j.version}</version>
        </dependency>

swagger 配置文件配置


# Swagger配置
swagger:
  enabled: true# 是否开启swagger 正式关键关闭 false
  title: 文档标题
  description: 文档说明
  termsOfServiceUrl: http://127.0.0.1:${server.port}/ # swagger 访问文档地址
  authorName: 作者名
  authorEmail: 1336809324@qq.com #作者邮箱
  authorUrl: 地址
  version: 1.0.1
  webBasePackage: com.dubug.middleware #web项目包路径
  apiBasePackage: com.dubug.middleware.controller #api接口层包路径

# knife开源的swagger ui配置
knife4j:
  # 配置认证功能
  basic:
    # 是否开启认证 正式环境关闭
    enable: true 
    # 用户名
    username: admin
    # 密码
    password: 123456

配置类对应的实体类

package com.dubug.middleware.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @Description
 * @Author swagger
 * @Version V1.0.0
 * @Date 2021/6/1 0001
 */
@Data
@ConfigurationProperties(prefix = "swagger") 
@Component
public class SwaggerProperties {
  /**
   * 是否启用
   */
  private boolean enabled;
  /**
   * 标题
   */
  private String title;

  /**
   * 文档描述
   */
  private String description;

  /**
   * 项目路径
   */
  private String termsOfServiceUrl;

  /**
   * 作者
   */
  private String authorName;

  /**
   * 邮箱
   */
  private String authorEmail;

  /**
   * 作者主页
   */
  private String authorUrl;

  /**
   * 版本
   */
  private String version;

  /**
   * web扫描的路径
   */
  private String webBasePackage;

  /**
   * API扫描的路径
   */
  private String apiBasePackage;
}

配置

/**
 * @Description
 * @Author swagger
 * @Version V1.0.0
 * @Date 2021/6/1 0001
 */
@Configuration
@EnableSwagger2
@EnableConfigurationProperties(value = SwaggerProperties.class)
@EnableKnife4j
@Import(BeanValidatorPluginsConfiguration.class)
@ConditionalOnProperty(value = {"swagger.enabled"}, matchIfMissing = true)
public class SwaggerConfiguration {

  @Bean(value = "createRestWeb")
  public Docket createRestWeb(SwaggerProperties swaggerProperties) {
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(
            new ApiInfoBuilder()
                .title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDescription())
                .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl())
                .contact(new Contact(swaggerProperties.getAuthorName(),
                    swaggerProperties.getAuthorUrl(),
                    swaggerProperties.getAuthorEmail()))
                .version(swaggerProperties.getVersion())
                .build()).groupName("后台 Web")
        .select()
          //apis() 控制哪些接口暴露给swagger,
                // RequestHandlerSelectors.any() 所有都暴露
                // RequestHandlerSelectors.basePackage("net.xdclass.*")  指定包位置
        .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) //标记有这个注解 ApiOperation
        .paths(PathSelectors.any())
        .build();
  }
}

放开关于swagger静态资源请求权限

/**
 * @Description
 * @Author config
 * @Version V1.0.0
 * @Date 2021/2/3 0003
 */
@Slf4j
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
  @Autowired
  private SwaggerProperties swaggerProperties;
  /**
   * 资源映射
   *
   * @param registry
   */
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (swaggerProperties.isEnabled()) {
      registry.addResourceHandler("doc.html","swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
      registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
  }
}

快速编写一个表的的增删改查

controller

package com.dubug.middleware.controller;

import com.dubug.middleware.constant.ResponseConst;
import com.dubug.middleware.entity.DbBook;
import com.dubug.middleware.mapper.DbBookMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
/**
 * @Description
 * @Author swagger
 * @Version V1.0.0
 * @Date 2021/6/22 0022
 */
@Api(tags = "图书模块", value = "SwaggerController")
@RestController
@RequestMapping("/api/swagger")
public class SwaggerController {

  @Autowired
  private DbBookMapper dbBookMapper;


  /**
   * 添加图书
   */
  @ApiOperation(value = "添加图书")
  @PostMapping("/insert")
  public void insertBook(@Valid @RequestBody DbBook dbBook) {
    dbBookMapper.insert(dbBook);
  }

  /**
   * 修改图书
   */
  @ApiOperation(value = "修改图书")
  @PostMapping("/update")
  public void updateBook(
      @Valid @RequestBody DbBook dbBook) {
    //需要验参Id
    Assert.notNull(dbBook.getId());
    dbBookMapper.updateByPrimaryKey(dbBook);
  }

  /**
   * 删除图书
   */
  @ApiOperation(value = "根据Id删除图书")
  @DeleteMapping("/delete_by_id")
  public void deleteById(
      @ApiParam(name = "id", value = "图书Id", example = "1")
      @RequestParam("id") String id) {
    dbBookMapper.deleteByPrimaryKey(id);
  }

  /**
   * 根据Id查询图书
   */
  @ApiOperation(value = "根据Id查询图书")
  @ApiResponses({
      @ApiResponse(code = ResponseConst.RIGHT_CODE, message = "查询成功"),
      @ApiResponse(code = ResponseConst.SYS_NOERROR, message = "查询失败")
   })
  @GetMapping("/select_by_id")
  public DbBook selectById(
            @ApiParam(name = "id", value = "图书Id", example = "1")
            @RequestParam("id") String id){
    return dbBookMapper.selectByPrimaryKey(id);
  }
}

领域模型类

package com.dubug.middleware.entity;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.constraints.NotBlank;
import java.io.Serializable;



@ApiModel("图书实体对象")
@Data
@Builder
public class DbBook implements Serializable {
    @ApiModelProperty(value = "书籍Id")
    private String id;

    @NotBlank
    @ApiModelProperty(value = "图书名称",required = true)
    private String bookName;

    @NotBlank
    @ApiModelProperty(value = "库存",required = true)
    private Integer stock;

}

访问接口文档

http://{ip地址}:{项目端口}/doc.html

页面如下
在这里插入图片描述

swagger注解说明

@Api

模块配置,用在controller类,描述API接口

@ApiOperation

接口配置,用在方法上,描述接口方法 

@ApiParam

方法参数配置,用在入参上面,描述参数

@ApiIgnore

忽略此接口不生成文档 

@ApiModel

  用于类 表示对类进行说明,用于参数用实体类接收,value–表示对象名,description–描述
这种一般用在post创建的时候,使用对象提交这样的场景

@ApiModelProperty()

用于方法,字段; 表示对model属性的说明或者数据操作更改
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏

@ApiResponse

描述接口响应

@ApiImplicitParams

用于方法
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

挚爱妲己~

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

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

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

打赏作者

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

抵扣说明:

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

余额充值