SpringBoot学习---第六篇:集成swagger2

Swagger 是一款让你更好的书写API文档的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。

Swagger 文档提供了一个方法,使我们可以用指定的 JSON 或者 YAML 摘要来描述你的 API,包括了比如 names、order 等 API 信息。你可以通过一个文本编辑器来编辑 Swagger 文件,或者你也可以从你的代码注释中自动生成。各种工具都可以使用 Swagger 文件来生成互动的 API 文档。

一、添加maven依赖

<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>

二、添加Swagger配置类

package com.example.demo.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
public class SwaggerConfig {

    private final String PACKAGENAME = "com.example.demo.controller";

    @Bean
    public Docket api() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()  // 选择那些路径和api会生成document
                .apis(RequestHandlerSelectors.basePackage(PACKAGENAME))  // 对PACKAGENAME路径下的所有api进行监控
                .paths(PathSelectors.any())  // 对所有路径进行监控
                .build();

        return docket;
    }

    @SuppressWarnings("deprecation")
    private ApiInfo apiInfo() {
        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("swagger test api")
                .description("springboot 集成 swagger2")
                .version("1.0")
                .termsOfServiceUrl("Terms of service")
                .license("swagger io")
                .licenseUrl("https://swagger.io/")
                .build();
        return apiInfo;
    }
}

@Configuration注解:表明它是一个配置类;

@EnableSwagger2注解:开启swagger2;

apiINfo()方法:配置一些基本的信息;

apis()方法:指定扫描的包会生成文档。

特别注意:配置了api文件也就是controller包的路径,不然生成的文档扫描不到接口。

效果图:

三、Restful 接口

在配置中 设置的 PACKAGENAME (com.example.demo.controller)下创建UserController:

package com.example.demo.controller;

import com.example.demo.model.Result;
import com.example.demo.model.ResultCode;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(value = "UserController", description = "用户操作", tags = {"API-UserController"})
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService service;

    //如果不指定RequestMethod,Swagger会把所有RequestMethod都输出
    @ApiOperation(value = "创建用户", notes = "根据User对象创建用户")
    @RequestMapping("/add")
    Result<Integer> insert(User record) {
        Result<Integer> result = new Result<>();
        try {
            int data = service.insert(record);
            result.setCode(ResultCode.SUCCESS.getCode())
                    .setMessage("SUCCESS")
                    .setData(data);

        } catch (Exception e) {
            result.setCode(ResultCode.FAIL.getCode())
                    .setMessage("错误")
                    .setData(null);
        }
        return result;
    }


    @ApiOperation(value = "根据ID删除用户", notes = "根据url的id来获取用户详细信息")
    @GetMapping("/delete/{id}")
    Result<Integer> delete(@PathVariable(value = "id") Integer id) {
        Result<Integer> result = new Result<>();
        try {
            int data = service.deleteByPrimaryKey(id);
            result.setCode(ResultCode.SUCCESS.getCode())
                    .setMessage("SUCCESS")
                    .setData(data);

        } catch (Exception e) {
            result.setCode(ResultCode.FAIL.getCode())
                    .setMessage("错误")
                    .setData(null);
        }
        return result;
    }


    @ApiOperation("更改用户信息")
    @PostMapping("/update")
    Result<Integer> updateById(User record) {
        Result<Integer> result = new Result<>();
        try {
            int data = service.updateByPrimaryKey(record);
            result.setCode(ResultCode.SUCCESS.getCode())
                    .setMessage("SUCCESS")
                    .setData(data);

        } catch (Exception e) {
            result.setCode(ResultCode.FAIL.getCode())
                    .setMessage("错误")
                    .setData(null);
        }
        return result;
    }

    @ApiOperation("获取用户详细信息")
    @RequestMapping(value = "get/{id}", method = RequestMethod.GET)
    Result<User> getUserById(@PathVariable(value = "id") Integer id) {
        Result<User> result = new Result<>();
        try {
            User user = service.selectByPrimaryKey(id);
            result.setCode(ResultCode.SUCCESS.getCode())
                    .setMessage("SUCCESS")
                    .setData(user);

        } catch (Exception e) {
            result.setCode(ResultCode.FAIL.getCode())
                    .setMessage("错误")
                    .setData(null);
        }
        return result;
    }

}

接收参数类:User.java

package com.example.demo.model;

import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class User implements Serializable{
    @ApiModelProperty(value = "用户ID")
    private Integer id;
    @ApiModelProperty(value = "姓名")
    private String name;
    @ApiModelProperty(value = "年龄")
    private Integer age;
}

Json返回输出类:Result.class

package com.example.demo.model;

import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;

public class Result<E> implements Serializable {
    @ApiModelProperty(value = "100成功, 其他为失败", required = true)
    private String code;
    @ApiModelProperty(value = "消息提示",required = true)
    private String message;
    @ApiModelProperty(value = "返回数据",required = true)
    private E data;

    public String getCode() {
        return code;
    }

    public Result<E> setCode(String code) {
        this.code = code;
        return this;
    }

    public String getMessage() {
        return message;
    }

    public Result<E>  setMessage(String message) {
        this.message = message;
        return this;
    }

    public E getData() {
        return data;
    }

    public Result<E>  setData(E data) {
        this.data = data;
        return this;
    }

    @Override
    public String toString() {
        return "Result{" +
                "code='" + code + '\'' +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }
}

四、swagger 文档

启动SpringBoot项目,访问 http://localhost:8080/swagger-ui.html

特别注意:

1. 如果不指定RequestMethod,Swagger会把所有RequestMethod都输出【例如上面的add方法】;

2. Spring4.3中引进了{@GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping}。

    例如@GetMapping等价于 @RequestMapping(method = RequestMethod.GET),即相当于指定了RequestMethod;

点开其中一个方法,例如:更改用户信息,如下图:

如果需要查看返回格式字段含义,可以点开 上图中 "Model":

五、swagger 注释API

5.1 常用注解汇总: 

 

API说明
@Api用于controller上,描述整个类
@ApiOperation用在controller的方法上,描述整个方法
@ApiParam用于方法,参数,字段说明 
@ApiImplicitParams用在controller的方法上,包含多个 @ApiImplicitParam
@ApiImplicitParam用在controller的方法上,表示单独的请求参数
@ApiModelProperty对model属性的说明
@ApiResponses用在controller的方法上
@ApiResponse用在 @ApiResponses里边

5.2 示例:

@ApiOperation(value = "方法说明", notes = "此接口描述xxxx功能")
@ApiResponses({
        @ApiResponse(code = 200, message = "请求成功"),
        @ApiResponse(code = 400, message = "请求失败"),
        @ApiResponse(code = 401, message = "未认证"),
        @ApiResponse(code = 404, message = "接口不存在"),
        @ApiResponse(code = 500, message = "服务器内部错误")
})
@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "query")
})
@RequestMapping(value = "/remove", method = RequestMethod.GET)
public void remove(Long id) {}
@ApiOperation(value="获取用户信息")
@GetMapping("/getUserInfo")
public User getUserInfo( @ApiParam(name="id", value="用户id", required=true) Long id) {    
   User user = new User();
   return user;
}
@ApiModelProperty(value = "用户ID")
private Integer id;
@ApiModelProperty(value = "姓名")
private String name;
 

5.3 @ApiImplicitParam 补充说明

ApiImplicitParam 的属性以及取值含义:name:接收参数名

  • value:接收参数的意义描述
  • required:参数是否必填
  • defaultValue:默认值
  • dataType:参数的数据类型 只作为标志说明,并没有实际验证
  • paramType:查询参数类型
    • path:以地址的形式提交数据
    • query:直接跟参数完成自动映射赋值
    • body:以流的形式提交 仅支持POST
    • header:参数在request headers 里边提交
    • form:以form表单的形式提交 仅支持POST

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值