SpringBoot2.X与Swagger2.X整合

由于业务需要,减少开发维护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", "[email protected]"))
                .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

在这里插入图片描述

Guess you like

Origin blog.csdn.net/qq_16771097/article/details/116302043