springboot3整合swagger2
时间: 2025-01-04 09:05:30 浏览: 4
在Spring Boot 3中整合Swagger 2可以通过以下步骤实现:
1. **添加依赖**:
首先,在你的`pom.xml`文件中添加Swagger 2的相关依赖:
```xml
<dependencies>
<!-- Swagger2 依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
```
2. **配置Swagger**:
创建一个配置类来配置Swagger:
```java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.any())
.build();
}
}
```
3. **启动应用并访问Swagger UI**:
启动你的Spring Boot应用,然后访问`http://localhost:8080/swagger-ui/`(默认端口是8080,具体端口根据你的应用配置可能有所不同)来查看Swagger UI。
4. **示例代码**:
下面是一个简单的示例,展示如何在Spring Boot 3中使用Swagger 2来生成API文档:
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
```java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
```
通过以上步骤,你就可以在Spring Boot 3中成功整合Swagger 2,并生成API文档。
阅读全文