SpringBoot 整合 Swagger2

Swagger的简介

  • 随着互联网技术的发展,现在的网站架构基本都由原来的后端渲染,变成了:前端渲染、前后端分离的形态,
    而且前端技术和后端技术在各自的道路上越走越远。前端和后端的唯一联系,变成了API接口;API文档变成
    了前后端开发人员联系的纽带,变得越来越重要,swagger 就是一款让你更好的书写 API 文档的框架。Swagger
    是全球最大的开源 API 开发工具框架,支持从设计到测试和部署的整个 API 生命周期的开发。
  • Swagger的出现就是为了方便进行测试后台的 restful(restful 是一种推荐的规范,该规范使用 put、post、get、delete 等指代增、改、查和删等)形式的接口,实现动态的更新,当我们在后台的接口修改了后,Swagger可以实现自动的更新,可以给前端人员提供自动测试方法

整合Swagger2的步骤

  • 在SpringBoot项目的pom.xml文件中引入依赖
<!-- Swagger2 -->
<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注解
常用注解描述
@Api修饰整个类,描述 Controller 的作用
@ApiOperation描述一个类的一个方法,或者说一个接口
@ApiParam单个参数描述
@ApiModel描述实体类
@ApiModelProperty描述实体类属性
@ApiProperty用对象接收参数时,描述对象的一个字段
@ApiResponseHTTP 响应其中 1 个描述
@ApiResponsesHTTP 响应整体描述
@ApiIgnore使用该注解忽略这个 API
@ApiError发生错误返回的信息
@ApiImplicitParam一个请求参数
@ApiImplicitParams多个请求参数
  • 编写Swagger配置类Swagger2,扫描SpringMVC控制器
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;

@Configuration
public class Swagger2Config {
	@Bean
	public Docket createRestApi() {
		//扫描控制器中 Swagger2 的注解, .apis里面的参数表示指定包
		return new Docket(DocumentationType.SWAGGER_2)
		.apiInfo(apiInfo())
		.select()
		 .apis(RequestHandlerSelectors.basePackage("com.rx.controller"))
		.paths(PathSelectors.any())
		.build();
	}
	//API 描述信息
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
		.title("springboot 利用 swagger 构建 api 文档")
		.description("简单优雅的 restful 风格")
		.termsOfServiceUrl("https://blog.csdn.net/Xu_Ren/article/details/105059039")
		.version("1.0")
		.build();
	}
}
  • 在启动类上,加上注解@EnableSwagger2 来开启 Swagger
  • 启动 SpringBoot 项目,测试路径:http://localhost:8080/swagger-ui.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值