欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

REST集成Swagger

程序员文章站 2022-05-05 13:20:18
...

1.添加maven依赖

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

2.配置Swagger

package com.rich.springboot.swagger;

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

/**
 * @author rich.liuchude
 * @since 2017-08-03 15:47
 */
@Configuration
@EnableSwagger2
public class Swagger {
    @Bean
    public Docket createDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.rich.springboot"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Rich LiuChude Web Server RESTful API")
                .description("RESTful接口")
                .termsOfServiceUrl("http://127.0.0.1:8080")
                .contact("aaa@qq.com")
                .version("1.0")
                .build();
    }
}

3.RestController

package com.rich.springboot.controller;

import com.rich.springboot.domain.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

/**
 * @author rich.liuchude
 * @since 2017-08-03 15:47
 */
@RestController
@Api(value = "测试API",description="测试接口")
public class WelcomeRestController {
    @ApiOperation(value = "组合注解", notes = "注意事项")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "int", name = "code", value = "返回码", required = true, paramType = "path"),
            @ApiImplicitParam(dataType = "JsonResult", name = "json", value = "返回值", required = true, paramType = "body")
    })
    @RequestMapping(value = "/query/{code}", method = RequestMethod.POST)
    public JsonResult query(@PathVariable int code, @RequestBody JsonResult json) {
        json.setCode(code);
        return json;
    }
}

4.访问Swagger
REST集成Swagger