linux

Linux Swagger与Spring Boot如何结合

小樊
41
2025-10-11 14:24:06
栏目: 智能运维

在Spring Boot项目中集成Swagger可以帮助你自动生成API文档,方便前后端分离开发和API的维护。以下是如何在Spring Boot项目中集成Swagger的步骤:

  1. 添加Swagger依赖: 在你的pom.xml文件中添加Swagger和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>
    

    请注意,Swagger 2.x版本适用于Spring Boot 2.x。如果你使用的是Spring Boot 3.x,你可能需要使用OpenAPI 3.x版本,即springdoc-openapi库。

  2. 配置Swagger: 创建一个配置类来配置Swagger。这个类需要使用@Configuration注解,并且包含一个方法来创建Docket bean。

    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();
        }
    }
    
  3. 访问Swagger UI: 启动你的Spring Boot应用程序后,你可以通过浏览器访问Swagger UI界面。默认情况下,URL是http://localhost:8080/swagger-ui.html

  4. 使用Swagger注解: 为了更好地控制API文档的生成,你可以在你的控制器和方法上添加Swagger注解。例如:

    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    
    @RestController
    @RequestMapping("/api")
    @Api(tags = "示例接口")
    public class ExampleController {
    
        @GetMapping("/hello")
        @ApiOperation("一个简单的示例接口")
        public String hello() {
            return "Hello, World!";
        }
    }
    
  5. 测试Swagger: 使用Swagger UI界面,你可以测试你的API端点,查看请求和响应的示例,以及发送实际的请求。

请注意,Swagger 2.x和OpenAPI 3.x之间有一些差异。如果你想要使用OpenAPI 3.x,你需要添加springdoc-openapi依赖,并且配置方式略有不同。上述步骤适用于Swagger 2.x。如果你需要OpenAPI 3.x的集成指南,请告诉我,我可以提供相应的信息。

0
看了该问题的人还看了