溫馨提示×

Debian系統中Swagger與Spring Boot如何集成

小樊
50
2025-09-19 05:52:18
欄目: 智能運維

在Debian系統中集成Swagger與Spring Boot,你需要遵循以下步驟:

  1. 創建Spring Boot項目: 如果你還沒有一個Spring Boot項目,你可以使用Spring Initializr(https://start.spring.io/)來生成一個。選擇必要的依賴項,例如Spring Web。

  2. 添加Swagger依賴: 在你的pom.xml文件中添加Swagger相關的依賴。對于Spring Boot 2.x,你可以使用springfox-swagger2和springfox-swagger-ui依賴:

    <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>
    

    對于Spring Boot 3.x,你需要使用springdoc-openapi依賴,因為springfox不再支持Spring Boot 3.x:

    <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-ui</artifactId>
        <version>1.6.9</version>
    </dependency>
    
  3. 配置Swagger: 創建一個配置類來設置Swagger。如果你使用的是springfox,你的配置類可能看起來像這樣:

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

    如果你使用的是springdoc-openapi,配置會更加簡單,因為它是自動配置的。

  4. 訪問Swagger UI: 啟動你的Spring Boot應用程序。一旦應用程序運行,你可以訪問Swagger UI界面來查看和測試你的API。默認情況下,Swagger UI可以通過以下URL訪問:

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

    對于springdoc-openapi,URL將是:

    http://localhost:8080/swagger-ui/index.html
    
  5. 編寫API文檔: 使用Swagger注解在你的控制器和方法上添加描述,這樣Swagger UI就可以顯示詳細的API文檔。

請注意,這些步驟假設你已經有了一個運行Debian系統的環境,并且已經安裝了Java和Maven。如果你還沒有安裝這些,你需要先安裝它們。此外,確保你的Spring Boot應用程序的端口沒有被其他服務占用,否則你可能需要更改默認端口。

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