linux

Linux中Swagger与Spring Boot如何结合

小樊
49
2025-09-20 14:09:22
栏目: 智能运维

在Linux环境下,将Swagger与Spring Boot结合使用可以让你更方便地构建和测试RESTful API。以下是详细的步骤指南:

1. 创建Spring Boot项目

首先,你需要创建一个Spring Boot项目。你可以使用Spring Initializr(https://start.spring.io/)来快速生成项目结构。

2. 解压并导入项目

解压下载的项目压缩包,并使用你喜欢的IDE(如IntelliJ IDEA、Eclipse等)导入项目。

3. 配置Swagger

使用Springfox Swagger2

  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. 配置Swagger: 创建一个配置类来配置Swagger:

    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.controller"))
                    .paths(PathSelectors.any())
                    .build();
        }
    }
    
  3. 访问Swagger UI: 启动Spring Boot应用程序后,访问http://localhost:8080/swagger-ui.html即可看到Swagger UI界面。

使用Springdoc OpenAPI

  1. 添加依赖: 在pom.xml文件中添加以下依赖:

    <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-ui</artifactId>
        <version>1.5.2</version>
    </dependency>
    
  2. 配置OpenAPI: Springdoc OpenAPI会自动配置Swagger UI,无需额外配置。

  3. 访问OpenAPI UI: 启动Spring Boot应用程序后,访问http://localhost:8080/swagger-ui/index.html即可看到OpenAPI UI界面。

4. 编写Controller

编写一个简单的Controller来测试Swagger:

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
@Api(tags = "示例接口")
public class ExampleController {

    @GetMapping("/hello")
    @ApiOperation("返回Hello World")
    public String hello() {
        return "Hello World";
    }
}

5. 启动应用程序

在终端中运行以下命令启动Spring Boot应用程序:

./mvnw spring-boot:run

6. 测试API

打开浏览器,访问http://localhost:8080/swagger-ui.html(或http://localhost:8080/swagger-ui/index.html),你应该能看到Swagger UI界面,并且可以测试你的API。

通过以上步骤,你就可以在Linux环境下成功地将Swagger与Spring Boot结合使用,从而更方便地构建和测试RESTful API。

0
看了该问题的人还看了