溫馨提示×

Linux Swagger與Spring Boot如何集成

小樊
54
2025-04-09 03:03:04
欄目: 智能運維

要在Spring Boot項目中集成Swagger,你需要遵循以下步驟:

  1. 添加依賴

在你的pom.xml文件中添加以下依賴:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

這里我們使用的是2.9.2版本的Swagger,你可以根據需要選擇其他版本。

  1. 配置Swagger

創建一個名為SwaggerConfig.java的新文件,并添加以下代碼:

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.controller"))
                .paths(PathSelectors.any())
                .build();
    }
}

在這個配置類中,我們定義了一個名為apiDocket bean。RequestHandlerSelectors.basePackage方法用于指定需要進行Swagger文檔生成的Controller所在的包名。PathSelectors.any()表示所有路徑都需要生成文檔。

  1. 訪問Swagger UI

啟動你的Spring Boot應用程序,然后在瀏覽器中訪問以下URL:

http://localhost:8080/swagger-ui.html

這里假設你的應用程序運行在8080端口上。你應該能看到Swagger UI界面,其中列出了你的API文檔。

現在你已經成功地將Swagger集成到了你的Spring Boot項目中。你可以使用Swagger UI來測試和瀏覽你的API。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女