SpringBoot整合Swagger2和坑

本文详细介绍如何在SpringBoot项目中集成Swagger2,包括添加依赖、配置类编写、注解使用及常见问题解决,帮助快速实现RESTful API文档自动生成与测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一. Swagger2简介

官网直达
Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。方便前后端分离类型接口的功能查看,和实际体验,减少了后台和前端沟通的成本。
本文简单介绍了在Springboot项目中集成swagger2的方式,和一些常见问题。

二. Springboot 整合Swagger2

具体整合方法很简单:

(1)加入依赖

https://mvnrepository.com 网站上搜索springfox即可得到最新版本的依赖:
在这里插入图片描述
点进去选择对应版本的依赖包就可以了,高版本的依赖需要的springboot版本也高,这里需要特别注意哦。
这里用的是Springboot Dalston.SR2版本(也就是1.5.x版本)+ swagger 2.7.0版本:在pom.xml中引入以下依赖:

		<!-- swagger2支持 -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.7.0</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.7.0</version>
		</dependency>

(2)配置Swagger2Config配置类:配置Swagger2的基本设置,【配置类和启动类放到同级】
package com.wdy;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
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;

/**
 * swagger2的配置文件,在项目的启动类的同级文件建立
 * 
 * @author wangdy 2018年11月19日
 */
@Configuration
public class Swagger2Config extends WebMvcConfigurerAdapter {
	// swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等,不然会扫描到spring一些api
	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
				// 为当前包路径
	.apis(RequestHandlerSelectors.basePackage("com.wdy.web.controller")).paths(PathSelectors.any()).build();
	}

	// 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				// 页面标题
				.title("SpringBoot 使用 Swagger2 构建RESTful API")
				// 创建人
				.contact(new Contact("wangdy", "https://blog.csdn.net/wdy_2099", ""))
				// 版本号
				.version("1.0.0")
				// 描述
				.description("API 描述文件").build();
	}

	/**
	 * 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。 需要重新指定静态资源
	 * 这个也是发生404的解决方案
	 * @param registry
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
		registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
	}
}

(3)在启动类上加入@EnableSwagger2注解,在启动程序是启动Swagger2,如下图:

在这里插入图片描述

(4)启动程序,访问http://localhost:8060/swagger-ui.html 查看结果如下:

在这里插入图片描述
这样,springboot和swagger2的整合就完成了。

三. Swagger2常用API

常用的注解有3个,一个在方法上使用(),一个在实体的属性上使用,一个在参数上直接使用。

(1)在方法上使用:@ApiOperation(value=“对具体方法的功能描述”)

在这里插入图片描述

(2)参数是对象的情况:在对象的属性上使用:@ApiModelProperty(value=“对具体属性的功能描述”)

在这里插入图片描述

(3)参数是普通参数的情况:在参数上使用:@ApiParam(value=“对具体参数的功能描述”)

在这里插入图片描述

(4)效果展示:

在这里插入图片描述
在这里插入图片描述
这就是3个最常用的API了,就是对请求方法,其实就是参数的中文的详细的描述。

(5)其他注解说明:
	1@Api(): 作用于类,标识这个类是干嘛的,通常用于Controller层;
		@Api(value="用户相关Controller",tags={"用户相关操作接口"})
		@RestController
		public class UserController{
			//...
		}
	2@ApiModel() 用于实体类,对于整个实体的描述; 
		@ApiModel(value="user对象",description="这是用户对象")
		public class User{
			//...
		}
	3@ApiResponse 用于方法,描述操作的可能响应。
	@ApiResponses: 用于方法,多种可能的响应集合
		@ApiResponses(value = { 
            @ApiResponse(code = 500, message = "500:服务器错误"),
            @ApiResponse(code = 500, message = "401:没有权限"),
            @ApiResponse(code = 500, message = "100:系统错误")
       })
 	  4@ApiImplicitParams:作用与方法,对各个请求参数进行统一描述。
       @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码,从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = "userId", value = "用户ID", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "operationType", value = "操作类型1收藏2分享3下载", paramType = "query", dataType = "String")
    })

至于其他API具体可以参考以下资料研究学习:
1)github: https://github.com/swagger-api
2)开放API :https://swagger.io/specification/

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一掬净土

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值