springboot+swagger2

Springboot + swagger2
swagger简介

​ Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步

作用
  1. 接口的文档在线自动生成。
  2. 功能测试。
Swagger使用的注解及其说明
@Api:用在类上,说明该类的作用。

@ApiOperation:注解来给API增加方法说明。

@ApiImplicitParams : 用在方法上包含一组参数说明。

@ApiImplicitParam:用来注解来给方法入参增加说明。
参数:
   ·paramType:指定参数放在哪个地方
      ··header:请求参数放置于Request Header,使用@RequestHeader获取
      ··query:请求参数放置于请求地址,使用@RequestParam获取
      ··path:(用于restful接口)-->请求参数的获取:@PathVariable
      ··body:(不常用)
      ··form(不常用)
   ·name:参数名
   ·dataType:参数类型
   ·required:参数是否必须传(true | false)
   ·value:说明参数的意思
   ·defaultValue:参数的默认值

@ApiResponses:用于表示一组响应

@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
      ——code:数字,例如400
      ——message:信息,例如"请求参数异常!"
      ——response:抛出异常的类   

@ApiModel:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)

@ApiModelProperty:描述一个model的属性
导入依赖
复制代码
        <!-- swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.4.0</version>
        </dependency>
编写swagger配置类

package com.wql.shop.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

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


@Configuration
@EnableSwagger2
@EnableKnife4j
public class SwaggerConfiguration {

    @Bean
    public Docket userApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("用户模块")  //分组
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.wql.shop"))//当前扫描包路径
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("swagger APIs")//标题信息
                .description("swaggerAPI")//描述
                .termsOfServiceUrl("http://www.nucarf.com")//自定义地址
                .contact("nucarf@mail.com")
                .version("9.9")
                .build();
    }

}

使用swagger提供的注解
controller层
package com.wql.shop.controller;

import com.wql.shop.service.UserServiceTest;
import com.wql.shop.service.impl.entity.UserAddress;
import com.wql.shop.service.impl.service.OrderService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Api(tags = "用户信息")
public class ConsumerController {

    @Autowired
    OrderService orderService;
    
    @Autowired
    UserServiceTest userService;

    @ApiOperation(value = "根据用户ID查询信息",tags ="用户信息" )
    @PostMapping("/order")
    @ApiResponses({@ApiResponse(code = 10000,message = "无效ID值"),
            @ApiResponse(code = 10001,message = "该ID值已过期")})
    public List<UserAddress> order(@RequestParam("userId") @ApiParam(name = "userId",value = "用户ID",required = true) String userId){
        List<UserAddress> userAddresses = orderService.initOrder(userId);

        return userAddresses;
    }

    @ApiOperation(value = "查询用户")
    @PostMapping("/select")
    @ApiResponses({
            @ApiResponse(code = 10000,message = "无效ID值"),
            @ApiResponse(code = 10001,message = "该ID值已过期"),
            @ApiResponse(code = 404,message = "请求不到资源"),
            @ApiResponse(code = 403,message = "未认证")
    })
    public void selectUser(Integer uId){
        userService.select(uId);
    }
}

实体层
package com.wql.shop.service.impl.entity;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;

@ApiModel(description = "用户信息")
public class UserAddress implements Serializable {

    @ApiModelProperty(value = "ID",example = "1",dataType = "整形")
    private Integer id;
    @ApiModelProperty(value = "用户地址",example = "北京")
    private String userAddress;  //用户地址
    @ApiModelProperty(value = "用户ID",example = "1001")
    private String userId;  //用户id
    @ApiModelProperty(value = "收货人",example = "张三")
    private String consignee;      //收货人
    @ApiModelProperty(value = "用户电话",example = "12345678910")
    private String phoneNum;//电话号码
    @ApiModelProperty(value = "是否默认地址",example = "1")
    private String isDefault;//是否默认地址


    public UserAddress() {
    }

    public UserAddress(Integer id, String userAddress, String userId, String consignee, String phoneNum, String isDefault) {
        this.id = id;
        this.userAddress = userAddress;
        this.userId = userId;
        this.consignee = consignee;
        this.phoneNum = phoneNum;
        this.isDefault = isDefault;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserAddress() {
        return userAddress;
    }

    public void setUserAddress(String userAddress) {
        this.userAddress = userAddress;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getConsignee() {
        return consignee;
    }

    public void setConsignee(String consignee) {
        this.consignee = consignee;
    }

    public String getPhoneNum() {
        return phoneNum;
    }

    public void setPhoneNum(String phoneNum) {
        this.phoneNum = phoneNum;
    }

    public String getIsDefault() {
        return isDefault;
    }

    public void setIsDefault(String isDefault) {
        this.isDefault = isDefault;
    }

    @Override
    public String toString() {
        return "UserAddress{" +
                "id=" + id +
                ", userAddress='" + userAddress + '\'' +
                ", userId='" + userId + '\'' +
                ", consignee='" + consignee + '\'' +
                ", phoneNum='" + phoneNum + '\'' +
                ", isDefault='" + isDefault + '\'' +
                '}';
    }
}

最后启动Spring Boot程序,访问 http://locahost:8080/swagger-ui.html

参考文献:
Swagger官网 :http://swagger.io/
Spring Boot & Swagger UI : http://fruzenshtein.com/spring-boot-swagger-ui/
Github:https://github.com/swagger-api/swagger-core/wiki/Annotations

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值