SpringBoot2.7.3 版本配置swagger3的方法及教程

时间:2022-09-11 20:50:13 类型:JAVA
字号:    

  对SpringBoot2.7.3版本,swagger2.x版本不再适用,所以就选择了swagger3版本,但是相较于swagger2版本,swagger3版本更加麻烦,具体教程如下:

  第一步:引入依赖

1
2
3
4
5
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

  第二步:在启动类Application中加上注解@EnableOpenApi

1
2
3
4
5
6
7
8
9
@EnableOpenApi
@SpringBootApplication
public class SpringBootApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(SpringBoot01Application.class, args);
    }
 
}

  第三步:配置接口文档config

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.example.springboot01.config;
 
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;
import springfox.documentation.service.Contact;
@Configuration
@EnableOpenApi
public class SwaggerConfiguration {
    @Bean
    public Docket createRestApi(){
 
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
 
    }
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("Swagger3接口文档")
                .description("前后端分离的接口文档")
                .contact(new Contact("庄子","http://www.ncyteng.com","3168765867@qq.com"))
                .version("1.0")
                .build();
    }
    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider) {
                    customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
                }
                return bean;
            }
 
            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(
                    List<T> mappings) {
                List<T> copy = mappings.stream().filter(mapping -> mapping.getPatternParser() == null)
                        .collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);
            }
 
            @SuppressWarnings("unchecked")
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    field.setAccessible(true);
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                }
                catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }
}

  第四步:在application.properties文件中加入语句

1
spring.mvc.pathmatch.matching-strategy=ant_path_matcher

 或者在application.yml中加入

1
2
3
4
spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

 第五步:打开浏览器地址栏输入

1
http://localhost:8001/swagger-ui/index.html

  注意:swagger2的网页路径为http:/localhost:8001/swagger-ui.html

1.jpg


Swagger3 的使用

  下面我们开始使用Swagger3,主要来介绍 Swagger3 中的几个常用的注解,分别在实体类上Controller 类上以及Controller 中的方法上,最后我们看一下 Swagger3 是如何在页面上呈现在线接口文档的,并且结合Controller 中的方法在接口中测试一下数据

实体类注解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
 
@Data
@ApiModel(value = "用户实体类")
public class User {
    @ApiModelProperty(value = "用户唯一标识")
    private Long id;
    @ApiModelProperty(value = "用户名")
    private String username;
    @ApiModelProperty(value = "用户密码")
    private String userpwd;
 
    public User(Long id, String username, String userpwd) {
        this.id = id;
        this.username = username;
        this.userpwd = userpwd;
    }
}

解释下 @ApiModel 和 @ApiModelProperty 注解:

  @ApiModel 注解用于实体类,表示对类进行说明,用于参数用实体类接收。

  @ApiModelProperty 注解用于类中属性,表示对 model 属性的说明或者数据操作更改。


Controller 类中相关注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@RestController
@RequestMapping("/swagger")
// @Api(value = "Swagger3在线接口文档")  swagger2使用value
@Api(tags = "Swagger3在线接口文档")  swagger3使用 tags
public class SwaggerController {
 
    @GetMapping("/get/{id}")
    @ApiOperation(value = "根据用户唯一标识获取用户信息")
    public JsonResult<User> getUserInfo(@PathVariable @ApiParam(value = "用户唯一标识") Long id) {
            // 模拟数据库中根据id获取User信息
            User user = new User(id, "zhuangzi""123456");
            return new JsonResult(user);
    }
 
}

我们来学习一下 @Api 、 @ApiOperation 和 @ApiParam 注解。

       @Api 注解用于类上,表示标识这个类是 swagger 的资源。

       @ApiOperation 注解用于方法,表示一个 http 请求的操作。

       @ApiParam 注解用于参数上,用来标明参数信息。


再次浏览信息页面信息

1.jpg

测试一下:

2.jpg

<