日韩精品欧美激情国产一区_中文无码精品一区二区三区在线_岛国毛片AV在线无码不卡_亞洲歐美日韓精品在線_使劲操好爽好粗视频在线播放_日韩一区欧美二区_八戒八戒网影院在线观看神马_亚洲怡红院在线色网_av无码不卡亚洲电影_国产麻豆媒体MDX

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

時間:2022-09-11 20:50:13 類型:JAVA
字號:    

  對SpringBoot2.7.3版本,swagger2.x版本不再適用,所以就選擇了swagger3版本,但是相較于swagger2版本,swagger3版本更加麻煩,具體教程如下:

  第一步:引入依賴

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

  第二步:在啟動類Application中加上注解@EnableOpenApi

@EnableOpenApi
@SpringBootApplication
public class SpringBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBoot01Application.class, args);
    }

}

  第三步:配置接口文檔config

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://tjegd.cn","[email protected]"))
                .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文件中加入語句

spring.mvc.pathmatch.matching-strategy=ant_path_matcher

 或者在application.yml中加入

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

 第五步:打開瀏覽器地址欄輸入

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

  注意:swagger2的網頁路徑為http:/localhost:8001/swagger-ui.html

1.jpg


Swagger3 的使用

  下面我們開始使用Swagger3,主要來介紹 Swagger3 中的幾個常用的注解,分別在實體類上Controller 類上以及Controller 中的方法上,最后我們看一下 Swagger3 是如何在頁面上呈現(xiàn)在線接口文檔的,并且結合Controller 中的方法在接口中測試一下數(shù)據

實體類注解:

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 注解用于實體類,表示對類進行說明,用于參數(shù)用實體類接收。

  @ApiModelProperty 注解用于類中屬性,表示對 model 屬性的說明或者數(shù)據操作更改。


Controller 類中相關注解

@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) {
            // 模擬數(shù)據庫中根據id獲取User信息
            User user = new User(id, "zhuangzi", "123456");
            return new JsonResult(user);
    }

}

我們來學習一下 @Api 、 @ApiOperation 和 @ApiParam 注解。

       @Api 注解用于類上,表示標識這個類是 swagger 的資源。

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

       @ApiParam 注解用于參數(shù)上,用來標明參數(shù)信息。


再次瀏覽信息頁面信息

1.jpg

測試一下:

2.jpg

<