Spring Boot 整合 Swagger3 如何生成接口文档?
在Spring Boot项目中整合Swagger3生成接口文档,你需要按照以下步骤操作:
- 添加Swagger3依赖到你的
pom.xml
文件中:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
- 创建Swagger配置类,通常是一个带有
@Configuration
注解的Java类:
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springdoc.core.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("Your API Title")
.version("1.0.0")
.license(new License().name("Your License").url("https://yourlicense.com")));
}
@Bean
public GroupedOpenApi publicApi() {
return GroupedOpenApi.builder()
.group("public-api")
.pathsToMatch("/api/v1/**")
.build();
}
}
- 在你的控制器类上使用Swagger注解来描述接口:
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/example")
@Tag(name = "Example Controller", description = "Example API Endpoints")
public class ExampleController {
@Operation(summary = "Get Example Data", description = "Returns example data")
@ApiResponse(responseCode = "200", description = "Successful response", content = @Content(schema = @Schema(implementation = String.class)))
@GetMapping("/data")
public String getExampleData() {
return "Example Data";
}
}
- 确保Spring Boot应用的主类上有
@EnableSwagger2
注解:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class YourApplication {
public static vo
评论已关闭