springboot集成Swagger3.0.0

在spring boot项目中
maven依赖:

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

建个config包,创建Swagger配置类如下,可直接复制使用

package com.ywp.springboot2022.config;

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.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import sp

### 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、付费专栏及课程。

余额充值