SpringBoot2.X与Swagger2.X整合

本文档介绍了如何通过引入Swagger2和SpringBoot的整合,减少API开发和维护的时间。配置包括Maven依赖、Swagger2的配置、启用Swagger以及在控制层添加注解。Swagger2提供了一个交互式的API文档,方便前后端接口联调。
摘要由CSDN通过智能技术生成

由于业务需要,减少开发维护API时间,便有了Swagger与SpringBoot的整合

引入Maven包

<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.9.2</version>
</dependency>
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.9.2</version>
</dependency>

配置swagger

package com.hello.springbootweb.config.swagger;

import com.google.common.base.Predicates;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;

/**
 * API接口界面--swagger-ui.html
 *
 * @Date 2020/9/30 9:00
 **/
@Configuration
@EnableSwagger2
public class Swagger2Config {

    @Value("${jwt.header}")
    private String tokenHeader;

    @Value("${jwt.token-start-with}")
    private String tokenStartWith;

    @Value("${swagger.enabled}")
    private Boolean enabled;

    @Value("${swagger.stu-url}")
    private String stuUrl;

    /**
     * 用于配置swagger2,包含文档基本信息
     * 指定swagger2的作用域(这里指定包路径下的所有API)
     *
     * @return Docket
     */
    @Bean
    public Docket createRestApi() {
        ParameterBuilder ticketPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>(1);
        ticketPar.name(tokenHeader).description("token").modelRef(new ModelRef("string"))
                .parameterType("header").defaultValue(tokenStartWith + " ").required(true).build();
        pars.add(ticketPar.build());
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(enabled)
                .apiInfo(apiInfo())
                .select()
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .build()
                .globalOperationParameters(pars);

//        return new Docket(DocumentationType.SWAGGER_2)
//                .apiInfo(apiInfo())
//                .select()
//                //指定需要扫描的controller
//                .apis(RequestHandlerSelectors.basePackage("com.hello.springbootweb.controller"))
//                .paths(PathSelectors.any())
//                .build();
    }

    /**
     * 构建文档基本信息,用于页面显示,可以包含版本、
     * 联系人信息、服务地址、文档描述信息等
     *
     * @return ApiInfo
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //标题
                .title("SpringBoot2-API")
                .description("通过访问swagger-ui.html,实现前后端接口联调")
                .termsOfServiceUrl(stuUrl + "/swagger-ui.html")
                //设置联系方式
                //.contact(new Contact("人工", "www.baidu.com", "xxxxx@qq.com"))
                .version("1.0")
                .build();
    }
}

开启swagger

#是否开启 swagger-ui
swagger:
  enabled: true
  stu-url: http://127.0.0.1:8090

其他:

#jwt
jwt:
  header: Authorization
  # 令牌前缀
  token-start-with: Bearer

控制层添加注解

/**
 * 用户管理--操作
 * @Date 2020/9/15 14:53
 **/ 
@Api(tags = "系统管理-用户管理")
@RestController
public class SysUserController {

    @Resource
    SysUserService sysUserService;

    /**
     * 模糊查询
     * @param sysUserVo
     * @return
     */
    @ApiOperation(value = "模糊查询", notes = "用户-模糊查询")
    @ApiImplicitParam(name = "sysUserVo", value = "新增对象JSON", required = true, dataType = "SysUserVo")
    @PostMapping("/api/sysUser/getList")
    public ResultData getList(@RequestBody(required=false) SysUserVo sysUserVo) {
        return sysUserService.getList(sysUserVo);
    }

    /**
     * 查询分页
     * @param sysUserVo
     * @param current
     * @param size
     * @return
     */
    @ApiOperation(value = "查询分页", notes = "用户-查询分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysUserVo", value = "新增对象JSON", required = true, dataType = "SysUserVo"),
            @ApiImplicitParam(name = "current", value = "当前页", required = true, dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页显示条数", required = true, dataType = "int")
    })
    @PostMapping("/api/sysUser/page/{current}/{size}")
    public ResultData selectByPage(@RequestBody(required=false) SysUserVo sysUserVo,
                                   @PathVariable("current") long current, @PathVariable("size") long size) {
        return sysUserService.selectByPage(sysUserVo, current, size);
    }

    /**
     * 详情
     * @param userId
     * @return
     */
    @ApiOperation(value = "详情", notes = "根据ID获取详情")
    @ApiImplicitParam(name = "userId", value = "主键,唯一标识", required = true, dataType = "int")
    @GetMapping("/api/sysUser/getInfo/{userId}")
    public ResultData getInfo(@PathVariable("userId") Long userId) {
        return sysUserService.getInfo(userId);
    }

    /**
     * 新增
     * @param sysUserVo
     * @return
     */
    @ApiOperation(value = "新增", notes = "添加一条信息")
    @ApiImplicitParam(name = "sysUserVo", value = "新增对象JSON", required = true, dataType = "SysUserVo")
    @PostMapping("/api/sysUser/add")
    public ResultData userAdd(@RequestBody SysUserVo sysUserVo) {
        return sysUserService.insertSysUser(sysUserVo);
    }

    /**
     * 删除
     * @param userId
     * @return
     */
    @ApiOperation(value = "删除", notes = "根据ID获取删除")
    @ApiImplicitParam(name = "userId", value = "主键,唯一标识", required = true, dataType = "int")
    @DeleteMapping("/api/sysUser/del/{userId}")
    public ResultData userDel(@PathVariable("userId") Long userId) {
        return sysUserService.delSysUser(userId);
    }

    /**
     * 修改
     * @param sysUserVo
     * @return
     */
    @ApiOperation(value = "修改", notes = "编辑一条信息")
    @ApiImplicitParam(name = "sysUserVo", value = "新增对象JSON", required = true, dataType = "SysUserVo")
    @PutMapping("/api/sysUser/upd")
    public ResultData userUpd(@RequestBody SysUserVo sysUserVo) {
        return sysUserService.updSysUser(sysUserVo);
    }
}

效果图

http://127.0.0.1:9090/swagger-ui.html

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值