SpringBoot集成Swagger(一) Java随

「这是我参与11月更文挑战的第7天,活动详情查看:2021最后一次更文挑战


相关文章

Java随笔记:Java随笔记

前言

  • 哈喽,不知道各位小伙伴们在公司中前后端联调是以什么方式的?
  • 说说我自己的吧~
+ 上家公司用的是Yapi,我们后端开发时为了方便都是在PostMan中测试接口。然后写好之后在Yapi中添加进去,将地址发给前端,前端进行调试。
+ 现在这家是使用Swagger,写的时候稍微麻烦点,但是联调的时候太爽歪歪了,啥都不用管,前端自己玩去吧!哈哈哈~
  • 当然,如果你们公司还是前后端不分离的话。。。以上的当我没说。。。
  • 既然工作中用到了,那么肯定要研究研究的,虽然这玩意很简单,但是还是可以学习学习的嘛!

一、SpringBoot集成Swagger

  • 首先新建一个SpringBoot项目,只需要web服务即可。
  • 新建方式可以看我以前的文章,在此不在赘述。创建一个SpringBoot项目的两种方式
  • 项目建好之后我们导入Swagger相关配置
+ 
1
2
3
4
5
6
7
8
9
10
11
12
xml复制代码<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger-ui</artifactId>
   <version>2.9.2</version>
</dependency>
  • 项目中新建Swagger的配置类
+ 
1
2
3
4
5
6
7
8
9
kotlin复制代码package com.dayu.dyswagger.config;

import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration //配置类
@EnableSwagger2// 开启Swagger2的自动配置
public class SwaggerConfig {  
}
  • 大体结构如下:
+ ![image-20211109210135313.png](https://gitee.com/songjianzaina/juejin_p14/raw/master/img/983094bc01380156f769847f29d6467e167ed50bcdccdb21e786ee2fa898051a)
+ ![image-20211109212000108.png](https://gitee.com/songjianzaina/juejin_p14/raw/master/img/e2e3572975e9f7f1ea68e721829136ac559d4da2176201da32b2ffb0d49324f7)
  • 恭喜你,Swagger已经成功被集成到SpringBoot项目中啦!
  • 至于为啥会有basic-error-controller这个玩意,,这是因为SpringBoot项目本身有个error的返回。
  • 比如随便输个路由看看:
+ ![image-20211109212220872.png](https://gitee.com/songjianzaina/juejin_p14/raw/master/img/ce4a276ad2c0a98690cce0aa3693058f0f132d837ad1d2b3372b146577c2a460)

二、自定义Controller

  • 新建SwaggerTestController
+ 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
kotlin复制代码/**
* @program: dyswagger
* @description: Swagger测试
* @author: DaYu
*/
@RestController
public class SwaggerTestController {

   @RequestMapping(value = "test-swagger",method = RequestMethod.GET)
   public String dyTest(){
       return "大鱼,你好呀!";
  }

}
  • 再次启动项目访问看看
+ ![image-20211109212446958.png](https://gitee.com/songjianzaina/juejin_p14/raw/master/img/3a84a4d3c8bf66a898bb7cdde7febd20399dfea9a9c9d94b65b75959e5a4c832)
  • 完美
  • 既然是水文,那么肯定要把一篇文章能讲完的东西分开来写呀~
  • 下一篇文章我们再继续详细解释下,SwaggerConfig里面的配置及源码讲解。
  • 对不起兄弟们,为了参加活动我也是拼了~
  • 请叫我大水笔

路漫漫其修远兮,吾必将上下求索~

如果你认为i博主写的不错!写作不易,请点赞、关注、评论给博主一个鼓励吧~hahah

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%