SpringBoot 使用Swagger2

版权声明:LT https://blog.csdn.net/LitongZero/article/details/84134418

SpringBoot 使用Swagger2

Swagger2是一个非常好用的接口测试插件。类似于POSTMAN,但是Swagger2是集成在项目中的,在开发接口时,很方便对接口进行测试。



1、引入Maven依赖

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

2、编写Swagger2配置

可在项目中的config目录中创建Swagger2Config类。

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

@Configuration
@EnableSwagger2
/**
 *
 * @author: LT
 * @date: 2018/10/8 16:51
 */
public class Swagger2Config {
	@Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //controller包位置
                .apis(RequestHandlerSelectors.basePackage("com.lt.web.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
        //此处的地址为你的端口地址+ /swagger-ui.html
        //此处地址也是访问swagger的地址。
                .description("http://localhost:18080/swagger-ui.html")
                .title("LTZ 接口测试  (Swagger2)")
                .version("1.0")
                .build();
    }
}

3、为Controller中的方法添加配置

/***
     * 新增用户
     * @param userReq
     * @return
     */
    @ApiOperation( value = "添加用户", notes = "添加用户")
    @RequestMapping(value ="/add",method = RequestMethod.POST)
    public @ResponseBody
    InterfaceResult addUser(@RequestBody User userReq){
        return userService.addUser(userReq);
    }

4、启动项目,访问地址

地址:http://localhost:18080/swagger-ui.html
注:我的端口为18080,可自行更改。
在这里插入图片描述


5、请求接口

GET请求,参数可以直接在输入框中填写

在这里插入图片描述

在这里插入图片描述
POST请求
在这里插入图片描述

封装JSON进行请求。


6、Swagger常用注解

@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiProperty:用对象接收参数时,描述对象的一个字段
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiIgnore:使用该注解忽略这个API
@ApiError:发生错误返回的信息
@ApiImplicitParam:一个请求参数
@ApiImplicitParams:多个请求参数

猜你喜欢

转载自blog.csdn.net/LitongZero/article/details/84134418