SpringBoot 集成Swagger3

说明:

1)、本文使用Spring2 集成Swagger3, 本想使用Springboot3+ jdk 17 集成Swagger3,  但是搜了一些资料,Spring 想引用swagger3 需要依赖降级使用Spring2 版本,不然会出现下图的报错信息, 或者使用Spring3 + springdoc 实现swagger的功能,可看SpringBoot3 集成Springdoc 实现Swagger3功能-CSDN博客

2)、本文功能可通过配置文件实现swagger的开启与关闭,默认token的开启、设置

1、引包

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.6</version>
    </parent>

   <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>
        <springfox.swagger3.version>3.0.0</springfox.swagger3.version>
    </properties>

 <dependencies>
     <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>${springfox.swagger3.version}</version>
        </dependency>
        <!-- 美化引用-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>3.0.3</version>
        </dependency>
 </dependencies>

2、配置

import com.google.common.collect.Sets;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.ArrayList;
import java.util.List;

/**
 * Swagger3
 * 目前springboot3对swagger3 版本有要求,使用3需要Springboot降到2
 * 原生地址 http://www.xx.xx/swagger-ui/index.html
 * 美化地址 http://www.xx.xx/doc.html
 * swagger2 地址http://www.xx.xx/swagger-ui.html
 */
@EnableOpenApi
@Configuration
public class Swagger3 {

    @Value("${swagger.enable}")
	private boolean enableSwagger = true;

	@Value("${swagger.token}")
	private String token = "X_TOKEN";

	@Value("${swagger.enable-token}")
	private boolean enableToken = true;

	/**
	 * API 页面展示信息
	 */
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				// 标题
				.title("接口文档")
				// 描述
				.description("测试接口文档,发布: http://www.xx.xx/swagger-ui/index.html")
				// 作者
				.contact(new Contact("zc", "", "xxx@qq.com"))
				// 版本
				.version("版本号:V1.0")
				.build();
	}

	@Bean
	public Docket createRestApi() {
		Docket docket = new Docket(DocumentationType.OAS_30).pathMapping("/")
				// 定义是否开启swagger
				.enable(enableSwagger)
				// 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
				.apiInfo(apiInfo())
				// 设置哪些接口暴露给Swagger展示
				.select()
				// 扫描所有有注解的api
				.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
				// 扫描指定包中的swagger注解
//				.apis(RequestHandlerSelectors.basePackage("com.zc.controller"))
				.paths(PathSelectors.any())
				.build()
				// 支持的通讯协议集合
				.protocols(Sets.newHashSet("http", "https"));
		if (enableToken) {
			// 授权信息设置,必要的header token等认证信息
			docket.securitySchemes(securitySchemes())
					// 授权信息全局应用
					.securityContexts(securityContexts());
		}
		return docket;

	}

	/**
	 * 设置授权信息
	 */
	private List<SecurityScheme> securitySchemes() {
		List<SecurityScheme> securitySchemes = new ArrayList<>();
		securitySchemes.add(new ApiKey(token, token, In.HEADER.toValue()));
		return securitySchemes;
	}

	/**
	 * 授权信息全局应用
	 */
	private List<SecurityContext> securityContexts() {
		List<SecurityContext> securityContexts = new ArrayList<>();
		securityContexts.add(SecurityContext.builder()
				.securityReferences(securityReferences())
				.forPaths(PathSelectors.any()).build());
		return securityContexts;
	}

	private List<SecurityReference> securityReferences(){
		List<SecurityReference> securityReferences = new ArrayList<>();
		securityReferences.add(new SecurityReference(
				token,
				new AuthorizationScope[]{new AuthorizationScope("global", "accessEverything")}));
		return securityReferences;
	}
}

3、配置文件说明

swagger:
  enable: true
  enable-token: true
  token: X_TOKEN

4、controller

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * @author zc
 * @date 2024/2/23 13:29
 * @desc
 */
@RestController
@RequestMapping("/test")
@Api(value = "测试接口", tags = "测试接口")
public class TestController {

    @GetMapping("/get")
    @ApiOperation(value = "webClient", notes = "webClient")
    public String test(){
        return "ok";
    }
}

5、展示

注意: 原生swagger3 地址和swagger 2 有所不同:http://www.xx.xx/swagger-ui/index.html

美化地址:http://www.xx.xx/doc.html

6、参考

SpringBoot整合Swagger3_springboot集成swagger3-CSDN博客

基于SpringBoot3从零配置SpringDoc_springdoc springboot3-CSDN博客

  • 9
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值