欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > javascript >内容正文

javascript

SpringBoot学习笔记(16)----SpringBoot整合Swagger2

发布时间:2024/7/5 javascript 24 豆豆
生活随笔 收集整理的这篇文章主要介绍了 SpringBoot学习笔记(16)----SpringBoot整合Swagger2 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

Swagger 是一个规范和完整的框架,用于生成,描述,调用和可视化RESTful风格的web服务

  http://swagger.io

  Springfox的前身是swagger-springmvc,是一个开源的API doc框架,可以将我们的Controller接口的方法以文档的形式展现,基于swagger,这样就方便开发人员不用在开发完接口服务之后还需要手写一份文档给需要的人。

  使用方式如下

  引入依赖:

  pom.xml文件

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

  编写配置类,并使用@EnableSwagger2开启支持swagger2,配置类如下

  

package com.wangx.boot.util;import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import static springfox.documentation.builders.PathSelectors.regex; @Configuration @EnableSwagger2 public class Swagger2Configuration { @Bean public Docket accessToker() { return new Docket(DocumentationType.SWAGGER_2). groupName("api")//定一组 .select()//选择那些路径和接口api会生成document .apis(RequestHandlerSelectors.basePackage(""))//拦截的包 .paths(regex("/api/.*"))//拦截该路劲下的接口 .build() //创建
          .apiInfo(apiInfo()); //配置说明 } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("测试项目")//标题 .description("springboot整合swagger")//描述 .termsOfServiceUrl("http://www.baidu.com")// .contact(new Contact("wangx", "http://baidu.com","1028106567@qq.com"))//联系人 .version("1.0")//版本 .build(); } }

  这样就会拦截api路劲下的所有接口并生成document.

  访问:http://localhost:8080/swagger-ui.html#/

  视图如下:

  

  可以查看接口的相关信息,并且也可以不用通过postman就可以测试接口了。相当的便利的。

  同时swagger也提供了一些注解可以让我们使用在类或者方法上

  Swagger的注解及作用。 

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

原文 SpringBoot学习笔记(16)----SpringBoot整合Swagger2

转载于:https://www.cnblogs.com/xiaoshen666/p/10844089.html

总结

以上是生活随笔为你收集整理的SpringBoot学习笔记(16)----SpringBoot整合Swagger2的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。