一篇文章带你搞定 SpringBoot 整合 Swagger2

Bertha 。 2022-12-17 10:59 327阅读 0赞

前后端分离后,维护接口文档基本上是必不可少的工作。
一个理想的状态是设计好后,接口文档发给前端和后端,大伙按照既定的规则各自开发,开发好了对接上了就可以上线了。当然这是一种非常理想的状态,实际开发中却很少遇到这样的情况,接口总是在不断的变化之中,有变化就要去维护,做过的小伙伴都知道这件事有多么头大!还好,有一些工具可以减轻我们的工作量,Swagger2就是其中之一,至于其他类似功能但是却收费的软件,这里就不做过多介绍了。

文章目录

    • 一、创建工程
    • 二、Swagger2 配置
    • 三、简单示例
    • 四、中文配置案例
    • 五、在 Security 中的配置

一、创建工程

创建 SpringBoot 工程项目,创建时只需要加入 spring-boot-starter-web 依赖即可,
Maven 仓库搜索 Swagger2 依赖:

在这里插入图片描述
在这里插入图片描述

  1. <dependency>
  2. <groupId>io.springfox</groupId>
  3. <artifactId>springfox-swagger2</artifactId>
  4. <version>2.9.2</version>
  5. </dependency>
  6. <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
  7. <dependency>
  8. <groupId>io.springfox</groupId>
  9. <artifactId>springfox-swagger-ui</artifactId>
  10. <version>2.9.2</version>
  11. </dependency>

二、Swagger2 配置

Swagger2的配置也是比较容易的,在项目创建成功之后,只需要开发者自己提供一个Docket的Bean即可,如下:

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import springfox.documentation.builders.ApiInfoBuilder;
  4. import springfox.documentation.builders.PathSelectors;
  5. import springfox.documentation.builders.RequestHandlerSelectors;
  6. import springfox.documentation.service.Contact;
  7. import springfox.documentation.spi.DocumentationType;
  8. import springfox.documentation.spring.web.plugins.Docket;
  9. import springfox.documentation.swagger2.annotations.EnableSwagger2WebFlux;
  10. @Configuration
  11. @EnableSwagger2
  12. public class Swagger2Config {
  13. @Bean
  14. Docket docket() {
  15. return new Docket(DocumentationType.SWAGGER_2)
  16. .select()
  17. .apis(RequestHandlerSelectors.basePackage("org.yolo.swagger2.controller"))
  18. .paths(PathSelectors.any())
  19. .build().apiInfo(new ApiInfoBuilder()
  20. //网站描述
  21. .description("接口文档的描述信息")
  22. .title("微人事项目接口文档")
  23. //联系人信息
  24. .contact(new Contact("yolo","blog.csdn.net","xxxx@gmail.com"))
  25. //版本
  26. .version("v1.0")
  27. .license("Apache2.0")
  28. .build());
  29. }
  30. }

这里提供一个配置类,首先通过@EnableSwagger2WebFlux注解启用Swagger2,然后配置一个Docket Bean,这个Bean中,配置映射路径和要扫描的接口的位置,在apiInfo中,主要配置一下Swagger2文档网站的信息,例如网站的title,网站的描述,联系人的信息,使用的协议等等。

三、简单示例

(1)定义 User

  1. public class User {
  2. private Integer id;
  3. private String username;
  4. private String address;
  5. //get,set 方法省略
  6. }

(2)定义 Controller

  1. @RestController
  2. public class UserController {
  3. @GetMapping("/user")
  4. public User getUserById(Integer id){
  5. User user = new User();
  6. user.setId(id);
  7. return user;
  8. }
  9. }

在这种 restful 风格的代码里,需要明确指定接口是什么请求(get/post 等),不能直接写成 requestMapping,不然前端会生成6个方法,get,post 等都能发,会比较混乱。

启动项目,访问:http://localhost:8080/swagger-ui.html

在这里插入图片描述
也可以配置成中文描述

四、中文配置案例

(1)对于参数的描述可以放在实体类中

  1. @ApiModel(value = "用户实体类",description = "用户信息描述类")
  2. public class User {
  3. @ApiModelProperty(value = "用户id")
  4. private Integer id;
  5. @ApiModelProperty(value = "用户名")
  6. private String username;
  7. @ApiModelProperty(value = "用户地址")
  8. private String address;
  9. //get,set 方法省略
  10. }

(2)创建接口

  1. @RestController
  2. @Api(tags = "用户数据接口")
  3. public class UserController {
  4. @ApiOperation(value = "查询用户", notes = "根据用户id查询用户")
  5. @ApiImplicitParam(name = "id", value = "用户id", required = true, defaultValue = "99")
  6. @GetMapping("/user")
  7. public User getUserById(Integer id) {
  8. User user = new User();
  9. user.setId(id);
  10. return user;
  11. }
  12. @ApiOperation(value = "删除用户", notes = "根据用户id删除用户")
  13. @ApiImplicitParam(name = "id", value = "用户id", required = true, defaultValue = "99")
  14. @ApiResponses({
  15. @ApiResponse(code = 200, message = "删除成功"),
  16. @ApiResponse(code = 500, message = "删除失败")
  17. })
  18. @DeleteMapping("/user/{id}")
  19. public void deleteUserById(@PathVariable Integer id) {
  20. System.out.println("deleteUserById:" + id);
  21. }
  22. @PutMapping("/user")
  23. @ApiImplicitParams({
  24. @ApiImplicitParam(name = "id", value = "用户id", required = true, defaultValue = "99"),
  25. @ApiImplicitParam(name = "username", value = "用户名", required = true, defaultValue = "javaboy")
  26. })
  27. @ApiOperation(value = "更新用户", notes = "根据用户id更新用户名")
  28. // @ApiIgnore
  29. public User updateUsernameById(String username, Integer id) {
  30. User user = new User();
  31. user.setId(id);
  32. user.setUsername(username);
  33. return user;
  34. }
  35. @PostMapping("/user")
  36. @ApiOperation(value = "添加用户", notes = "添加用户接口")
  37. public User addUser(@RequestBody User user) {
  38. return user;
  39. }
  40. }

(1)@Api注解可以用来标记当前Controller的功能。
(2)@ApiOperation注解用来标记一个方法的作用。
(3)@ApiImplicitParam注解用来描述一个参数,可以配置参数的中文含义,也可以给参数设置默认值,这样在接口测试的时候可以避免手动输入。
(4)如果有多个参数,则需要使用多个@ApiImplicitParam注解来描述,多个@ApiImplicitParam注解需要放在一个@ApiImplicitParams注解中。
(5)需要注意的是,@ApiImplicitParam注解中虽然可以指定参数是必填的,但是却不能代替@RequestParam(required = true),前者的必填只是在Swagger2框架内必填,抛弃了Swagger2,这个限制就没用了,所以假如开发者需要指定一个参数必填,@RequestParam(required = true)注解还是不能省略。

(3)效果展示

在这里插入图片描述
可以看到,所有的接口这里都列出来了,包括接口请求方式,接口地址以及接口的名字等,点开一个接口,可以看到如下信息:

在这里插入图片描述
可以看到,接口的参数,参数要求,参数默认值等等统统都展示出来了,参数类型下的query表示参数以key/value的形式传递,点击右上角的Try it out,就可以进行接口测试:

点击Execute按钮,表示发送请求进行测试。测试结果会展示在下面的Response中。

小伙伴们注意,参数类型下面的query表示参数以key/value的形式传递,这里的值也可能是bodybody表示参数以请求体的方式传递,例如上文的更新接口,如下:

在这里插入图片描述
当然还有一种可能就是这里的参数为path,表示参数放在路径中传递,例如根据id查询用户的接口:

在这里插入图片描述

五、在 Security 中的配置

如果我们的Spring Boot项目中集成了Spring Security,那么如果不做额外配置,Swagger2文档可能会被拦截,此时只需要在Spring Security的配置类中重写configure方法,添加如下过滤即可:

  1. @Override
  2. public void configure(WebSecurity web) throws Exception {
  3. web.ignoring()
  4. .antMatchers("/swagger-ui.html")
  5. .antMatchers("/v2/**")
  6. .antMatchers("/swagger-resources/**");
  7. }

如此之后,Swagger2文件就不需要认证就能访问了。

发表评论

表情:
评论列表 (有 0 条评论,327人围观)

还没有评论,来说两句吧...

相关阅读