swagger配置及注解详解

swagger配置及注解详解

1.加入依赖的jar包

 <!--引入swagger的依赖-->
     <dependency>
         <groupId>io.springfox</groupId>
         <artifactId>springfox-swagger2</artifactId>
         <version>2.9.2</version>
     </dependency>

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

2.配置swagger配置文件

添加配置文件如下:

package com.hubiao.pay.common.merchant.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
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;

/**
 * Swagger2的接口配置
 *
 * @author hubiao
 */
@Configuration
@ConditionalOnProperty(prefix = "swagger",value = {"enable"},havingValue = "true")
@EnableSwagger2
public class SwaggerConfig {
    /**
     * 创建API
     */
    @Bean
    public Docket createRestApi() {
        return new Docket( DocumentationType.SWAGGER_2 )
                // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
                .apiInfo( apiInfo() )
                // 设置哪些接口暴露给Swagger展示
                .select()
                // (第一种方式)扫描所有有注解的api,用这种方式更灵活
                .apis( RequestHandlerSelectors.withMethodAnnotation( ApiOperation.class ) )
                // (第二种方式)扫描指定包中的swagger注解
                //.apis(RequestHandlerSelectors.basePackage("com.hubiao.pay.merchant.controller"))
                // (第三种方式)扫描所有 
                //.apis(RequestHandlerSelectors.any())
                .paths( PathSelectors.any() )
                .build();
    }

    /**
     * 添加摘要信息
     */
    private ApiInfo apiInfo() {
        // 用ApiInfoBuilder进行定制
        return new ApiInfoBuilder()
                // 设置标题
                .title( "标题:蚂蚁支付-商户应用API文档" )
                // 描述
                .description( "描述:向前端提供商户应用的ResultFul风格接口文档" )
                // 作者信息
                .contact( "hubiao" )
                // 版本
                .version( "版本号:" + "V1.0.0" )
                .build();
    }
}

3.生成swagger文档

package com.hubiao.pay.common.merchant.controller;

import com.hubiao.pay.merchant.api.MerchantService;
import com.hubiao.pay.merchant.api.dto.MerchantDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Description
 *
 * @author hubiao
 * @since 2020-11-01 21:51
 */
@Api(description = "商户平台应用接口")
@RestController
public class MerchantController {

    @org.apache.dubbo.config.annotation.Reference
    private MerchantService merchantService;


    /**
     * 根据id获取商户信息
     * @param id
     * @return
     */
    @ApiOperation( "根据商户id获取商户信息" )
    @GetMapping("/merchants/{id}")
    public MerchantDTO queryMerchantById(@PathVariable("id") Long id){
        return merchantService.queryMerchantById( id );
    }

    @ApiOperation( value = "测试swagger其他常用注解",httpMethod = "POST")
    @PostMapping("/hello")
    @ApiImplicitParam(name = "id", value = "商户id", dataType = "Long", paramType ="query", required = true)
    public String hello(Long id){
        return "hello "+ merchantService.queryMerchantById( id ).getMerchantName();
    }

}

在这里插入图片描述

4.使用swagger请求接口测试

  1. 点击try it out(试一试)
    在这里插入图片描述
    2.输入参数,点击提交请求
    在这里插入图片描述
    3.各种返回参数介绍
    在这里插入图片描述

5.swagger常用注解

在类中添加swagger注解即可生成swagger接口文档,常用注解如下

@Api:修饰整个类,描述的是controller的作用,写在类的名称上面;
@Api(value = "/merchant", description = "商户管理")
属性名称备注
valueurl的路径值
tags如果设置这个值、value的值会被覆盖
description对api资源的描述
basePath基本路径可以不配置
position如果配置多个Api 想改变显示的顺序位置
producesFor example, “application/json, application/xml”
consumesFor example, “application/json, application/xml”
protocolsPossible values: http, https, ws, wss.
authorizations高级特性认证时配置
@ApiOperation:修饰类的一个方法,用来描述该方法的作用,写在方法上;
 @ApiOperation(value = "商户新增", httpMethod = "POST")
属性名称备注
valueurl的路径值
tags如果设置这个值、value的值会被覆盖
description对api资源的描述
basePath基本路径可以不配置
position如果配置多个Api 想改变显示的顺序位置
producesFor example, “application/json, application/xml”
consumesFor example, “application/json, application/xml”
protocolsPossible values: http, https, ws, wss.
authorizations高级特性认证时配置
hidden配置为true 将在文档中隐藏
response返回的对象
responseContainer这些对象是有效的 “List”, “Set” or “Map”.,其他无效
httpMethod“GET”, “HEAD”, “POST”, “PUT”, “DELETE”, “OPTIONS” and “PATCH”
codehttp的状态码 默认 200
extensions扩展属性
@ApiParam:用对象来接收参数
public ResponseEntity<Merchant> merchantAdd(@RequestBody @ApiParam(value = "Merchant", required = true)  Merchant merchant)
属性名称备注
name属性名称
value属性值
defaultValue默认属性值
allowableValues可以不配置
required是否属性必填
access不过多描述
allowMultiple默认为false
hidden隐藏该属性
example举例子
@ApiModelProperty:用对象接受参数时,用来描述对象中一个字段的作用
@ApiModelProperty("名称")
private String name;
@ ApiResponses :HTTP响应整体的描述,响应集配置
@ApiResponses({ @ApiResponse(code = 400, message = "无效得商户") })
@ ApiResponse :HTTP响应其中一个的描述, 响应集配置
@ApiResponse(code = 400, message = "提供无效得用户")
属性名称备注
codehttp的状态码
message描述
response默认响应类 Void
reference参考ApiOperation中配置
responseHeaders参考 ResponseHeader 属性配置说明
responseContainer参考ApiOperation中配置
@ApiImplicitParams:用在方法上包含一组参数说明;
   @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "商户id", dataType = "Long", required = true, paramType = "query"),
            @ApiImplicitParam(name = "name", value = "商户名称", dataType = "string", paramType = "query", required = true)
    })
@ApiImplicitParam:用在方法上包含一个参数说明;
 @ApiImplicitParam(name = "id", value = "商户id", dataType = "Long", required = true, paramType = "query")
属性名称备注
paramType参数放在哪个地方
name参数代表的含义
value参数名称
dataType参数类型,有String/Long…
required是否必填
defaultValue参数的默认值
  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个开源的Java开发框架,而Swagger是一个用于构建、发布、文档化和管理API的工具。下面详细介绍如何在Spring Boot中整合Swagger。 首先,你需要在pom.xml文件中添加Swagger的依赖项。在<dependencies>标签中添加以下代码: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.10.5</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.10.5</version> </dependency> ``` 然后,你需要在Spring Boot的配置类中添加相关的注解配置。创建一个SwaggerConfig.java文件,添加以下代码: ```java @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("your.package.name")) .paths(PathSelectors.any()) .build(); } @Bean public UiConfiguration uiConfig() { return new UiConfiguration(null, "list", "alpha", "schema", UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS, false, true, 60000L); } } ``` 在上面的代码中,你需要将"your.package.name"替换为你的应用程序的包名。这将扫描该包下的所有控制器,生成API文档。 接下来,你可以启动你的Spring Boot应用程序,并访问"http://localhost:8080/swagger-ui.html"来查看生成的API文档。你将看到所有的控制器和它们的方法以及相关的参数和注释。 如果你想修改API的文档信息,你可以使用Swagger中的注解来添加说明和标注。例如,你可以在控制器的方法上添加@ApiOperation注解来描述该方法的作用。 综上所述,将Swagger整合到Spring Boot中是很简单的。你只需要添加依赖项,配置SwaggerConfig类,然后访问Swagger UI来查看生成的API文档。同时,你可以使用Swagger注解来进一步完善API文档。希望这个教程可以帮助你理解如何在Spring Boot中使用Swagger
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值