SpringBoot 集成Swagger3

说明:

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

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-优快云博客

基于SpringBoot3从零配置SpringDoc_springdoc springboot3-优快云博客

### Spring Boot 整合 Swagger3 实现 API 文档自动化生成与测试 #### 项目准备 为了使Spring Boot应用程序支持Swagger3并实现API文档的自动生成以及提供在线测试功能,需先确保项目的构建工具配置文件`pom.xml`中包含了必要的依赖项。具体来说,应当加入用于集成Swagger UI和支持OpenAPI 3.0规范描述格式的相关库[^4]。 ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> ``` #### 主应用类设置 接着,在主启动类上添加特定注解来启用增强版的Swagger界面组件——Knife4j,这将为用户提供更加友好美观的操作体验。例如: ```java package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; @SpringBootApplication @EnableSwagger2WebMvc // 启用Swagger Web MVC支持 public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 需要注意的是,对于最新版本的SpringFox(即3.x系列),推荐使用`@EnableSwagger2WebMvc`而非旧式的`@EnableSwagger2`以获得更好的兼容性和性能表现[^3]。 #### 配置Swagger属性 创建一个新的Java配置类用来定义Swagger的具体行为参数,比如基本信息、联系人详情等。下面是一个简单的例子说明如何完成这项工作: ```java @Configuration public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.OAS_30) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder().title("API Title") .description("Description of APIs") .contact(new Contact("Name", "URL", "Email")) .license("License") .licenseUrl("http://url-to-license.com") .version("1.0.0") .build(); } } ``` 这段代码片段展示了怎样通过Docket对象定制化Swagger的行为模式,并指定了扫描控制器所在的包路径以便于自动收集API元数据信息。 #### 访问Swagger UI 一旦上述步骤全部完成后,重启Spring Boot服务端口,默认情况下可以通过浏览器访问`http://localhost:<port>/doc.html`地址查看由Knife4j提供的改进型Swagger UI页面,这里可以浏览到所有已注册的服务接口及其详细说明,同时也允许直接在此界面上发起请求来进行交互式测试操作[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值