debian

Debian系统中Swagger与Spring Boot如何集成

小樊
54
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
看了该问题的人还看了