关于程序员:Springboot整合swagger2

2次阅读

共计 4384 个字符,预计需要花费 11 分钟才能阅读完成。

前言

最近新入职了一家公司,我的项目开发结束发现没有写接口的 API 文档工具,问了一下组长,组长通知我说平时都是口头交换调试,用不着接口文档 …… 想着能少费点口水,于是简略就整合一个 swagger2,上面贴上代码。

Jar 包依赖

咱们用的是 Maven 我的项目,所以间接在 pom.xml 中进行依赖,因为咱们我的项目应用的 Springboot-1.3.5,所以依赖比拟低,如果是高版本的小伙伴,能够自行下载对应的版本依赖。

附上 maven 仓库地址:https://mvnrepository.com/search?q=swagger2

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

配置类

而后咱们须要新建一个 swagger 配置类

package net.XXXX.xx.config;

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.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import springfox.documentation.service.Parameter;
import springfox.documentation.builders.ParameterBuilder;

import java.util.ArrayList;
import java.util.List;


@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("net.XXX.xx"))// 这里是本人的包构造
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(globalOperation());
    }

    private ApiInfo apiInfo() {return new ApiInfoBuilder()
                .title("接口示例文档")
                .description("接口文档 Demo")
                .version("1.0")
                .build();}
    
    // 上面代码能够酌情处理,因为咱们接口须要有 token 验证,所以须要配置一下 token 输入框,上面代码就是做这个性能的
    private List<Parameter> globalOperation(){
        // 增加 head 参数配置 start
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>();
        // 第一个 token 为传参的 key,第二个 token 为 swagger 页面显示的值
        tokenPar.name("token").description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        pars.add(tokenPar.build());
        return pars;
    }

} 

留神

如果大家我的项目中有过滤器,须要将 swagger 的拜访地址开释掉,将以下地址进行开释。

swagger-resources/*
swagger-ui.html/*
v2/*
webjars/*

示例 Controller

这里咱们用一个 GET 申请做一下示例,标注一下 Controller 以及参数,请疏忽代码内容~

@Api(value = "RevenueBudgetReisterController", description = "支出估算注销 API")
@RestController
@RequestMapping("/revenueBudgetRegister")
public class RevenueBudgetReisterController extends BaseController {

    private RevenueBudgetRegisterService registerService;

    @Autowired
    public RevenueBudgetReisterController(RevenueBudgetRegisterService registerService) {this.registerService = registerService;}    
    
    @ApiOperation(value = "获取一条记录", notes = "获取估算的明细记录")
    @ApiImplicitParams({@ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dictionaryName", value = "科目名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "departmentId", value = "部门 ID", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/v1.0/revenueBudgetTetails", method = RequestMethod.GET)
    public ResultDto revenueBudgetTetails(String year, String dictionaryName, String departmentId) {if (null == year || year.equals("")
                || null == departmentId || "".equals(departmentId)) {return new ResultDto(ResultDto.CODE_FAIL, RevenueBudgetDetailsController.ERROR_DATA, null);
        }
        List<RevenueBudgetDetailsVo> details = registerService.details(year, dictionaryName, departmentId);
        return new ResultDto(ResultDto.CODE_SUCCESS, RevenueBudgetDetailsController.SUCCEEDED, details);

    }
}

我的项目启动

拜访地址:http://localhost:8006/swagger-ui.html#/     地址端口号大家请更改为与本人绝对应的,我这里设置的是 8006

bingo!~  呈现这个界面就示意胜利了!(老汉冲动摸了摸本人的秃头,从轮椅上站了起来,流下了开心的泪水 …..)

而后咱们轻易点进去一个

这里会显示咱们接口的入参,以及申请形式等信息,如果咱们配置了 token 输入框,这里则会显示进去。

对于启动问题

可能集成 swagger 会呈现上面这个异样。

 集成 swagger2 报错:java.lang.NoSuchMethodError: com.google.common.XXX

呈现这个异样是因为 swagger 中内置了一个谷歌的 guava 包,而我的项目中也有 guava 的依赖,版本不统一导致的抵触,咱们须要将版本进行匹配,或者将低版本的依赖给排除掉,我这里升高了版本,原本我的项目中依赖的是 swagger-2.9.2 的版本,于是升高到了 swagger-2.4.0 版本,完满解决~

Swagger 罕用注解

swagger 通过注解表明该接口会生成文档,包含接口名、申请办法、参数、返回信息的等等。

  • @Api:润饰整个类,形容 Controller 的作用
  • @ApiOperation:形容一个类的一个办法,或者说一个接口
  • @ApiParam:单个参数形容
  • @ApiModel:用对象来接管参数
  • @ApiProperty:用对象接管参数时,形容对象的一个字段
  • @ApiResponse:HTTP 响应其中 1 个形容
  • @ApiResponses:HTTP 响应整体形容
  • @ApiIgnore:应用该注解疏忽这个 API
  • @ApiError:产生谬误返回的信息
  • @ApiParamImplicitL:一个申请参数
  • @ApiParamsImplicit:多个申请参数
  • @ApiImplicitParams:用在申请的办法上,示意一组参数阐明
  • @ApiImplicitParam:参数阐明,用在 @ApiImplicitParams 中

本次教程就到这里了,谢谢大家浏览,写的有不对的中央还请多多包涵以及提出!

正文完
 0