swagger2:两分钟学会swagger

2017-12-12  本文已影响0人  昔年_小武

学习背景

或许我们习惯用postman调试接口,但是你会发现,每次调试一个接口时都需要把路径和参数写上去,有的时候还容易写错,大大耽误了咱们的开发时间。

swagger是什么东西?

swagger用于定义API文档。

优点

实践

第一步:

在maven 中加入下面俩个依赖,一定是2.6.1之后的,之前的我试过几个不能用:

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.6.1</version>
        <scope>compile</scope>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.6.1</version>
        <scope>compile</scope>
    </dependency>
第二步:

写一个配置类:

@EnableSwagger2
@Configuration
class Swagger2 {
@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()  //RequestHandlerSelectors.any(),所有的路劲都去扫描
            //这个扫描包的意思一样,固定路劲就去相应的路劲扫描
            .apis(RequestHandlerSelectors.basePackage("com.example.demo.talkCloud.controller"))
            .paths(PathSelectors.any())
            .build();
}

//就是对生成的api文档的一个描述
private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
            .title("文档标题")
            .description("文档描述")
            .termsOfServiceUrl("相关url")
            .contact("名字-UP主")
            .version("版本:1.0")
            .build();
    }
 }

【注意】:实现这两步就能完成文档的生成了,可以尝试用localhost:8080/swagger-ui.html 访问,端口是spring boot 启动时设置的,自己看。

第三步:

去你的controller层用注解标记Controller,常用的注解我写在下面了,这些注解都是为了丰富api文档诞生的。这里先举个例如:

@ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "Authorization token",
                required = true, dataType = "string", paramType = "header"),
        @ApiImplicitParam(name = "studentId", value = "学生id", dataType = "Long", paramType = "query"),
        @ApiImplicitParam(name = "subjectId", value = "科目id", dataType = "Integer", paramType = "query"),
        @ApiImplicitParam(name = "pageSize", value = "页大小", dataType = "Integer", paramType = "query"),
        @ApiImplicitParam(name = "pageNo", value = "第几页", dataType = "Integer", paramType = "query"),
})
@ApiOperation(value = "学生课程表获取", httpMethod = "GET", response = ResponseEntity.class)
@RequestMapping(value = "student/course/table", method = RequestMethod.GET)
public ResponseEntity saveResourceSec(
        @RequestParam(name = "studentId") Long studentId,
        @RequestParam(name = "subjectId", required = false) Integer subjectId,
        @RequestParam(value = "pageSize", defaultValue = "25") Integer pageSize,
        @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
        @RequestParam(value = "modifiedOn", required = false) Date modifiedOn

) {
    PageWrapper<CourseScheduleObject> result = studentCourseTableService.getStudentCourseById(studentId, subjectId, pageNo, pageSize, modifiedOn);

    return ResponseEntity.ok(result);
}

【常见注解解读】

其实自己领悟一下就好,就按照单词表名意思,简单!

上一篇 下一篇

猜你喜欢

热点阅读