目录

SpringBoot集成Swagger指南

SpringBoot集成Swagger指南

在Spring Boot项目中集成Swagger可以帮助你自动生成API文档,并且提供一个交互式的UI界面,方便开发者测试和调试API。以下是集成Swagger的步骤:

1. 添加Swagger依赖

首先,在你的 pom.xml 文件中添加Swagger的依赖项。通常使用的是 springfox-swagger2springfox-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及以上版本, springfox 可能不再兼容,建议使用 springdoc-openapi

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.0.2</version>
</dependency>

2. 配置Swagger

接下来,你需要配置Swagger。创建一个配置类来启用Swagger并设置一些基本信息。

使用 springfox-swagger2 的配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
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()
                .apiInfo(new ApiInfoBuilder()
                        .title("Spring Boot API")
                        .description("API文档")
                        .version("1.0")
                        .build());
    }
}
使用 springdoc-openapi 的配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;

@Configuration
public class SwaggerConfig {

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("Spring Boot API")
                        .version("1.0")
                        .description("API文档"));
    }
}

3. 启动项目并访问Swagger UI

完成上述配置后,启动你的Spring Boot项目。然后,你可以通过以下URL访问Swagger UI界面:

  • 使用 springfox-swagger2http://localhost:8080/swagger-ui.html
  • 使用 springdoc-openapihttp://localhost:8080/swagger-ui.htmlhttp://localhost:8080/swagger-ui/index.html

4. 使用Swagger注解

你可以在Controller和Model上使用Swagger的注解来进一步定制API文档。

常用注解
  • @Api
    用于类上,表示这个类是Swagger的资源。
  • @ApiOperation
    用于方法上,表示一个HTTP请求的操作。
  • @ApiParam
    用于参数上,表示对参数的说明。
  • @ApiModel
    用于模型类上,表示对模型的说明。
  • @ApiModelProperty
    用于模型类的属性上,表示对属性的说明。
示例
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
@Api(tags = "用户管理")
public class UserController {

    @GetMapping("/user/{id}")
    @ApiOperation(value = "获取用户信息", notes = "根据用户ID获取用户信息")
    public String getUser(@ApiParam(value = "用户ID", required = true) @PathVariable Long id) {
        return "User " + id;
    }

    @PostMapping("/user")
    @ApiOperation(value = "创建用户", notes = "创建一个新用户")
    public String createUser(@ApiParam(value = "用户名", required = true) @RequestParam String name) {
        return "User " + name + " created";
    }
}

5. 自定义Swagger UI

你可以通过修改Swagger的配置来自定义UI界面,例如更改主题、添加自定义CSS等。

6. 生产环境禁用Swagger

在生产环境中,你可能不希望暴露Swagger UI。可以通过配置来禁用Swagger:

spring:
  profiles: prod
  swagger:
    enabled: false

然后在代码中根据配置决定是否启用Swagger:

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .enable(swaggerEnabled) // 根据配置决定是否启用
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.demo"))
            .paths(PathSelectors.any())
            .build()
            .apiInfo(apiInfo());
}

总结

通过以上步骤,你可以在Spring Boot项目中成功集成Swagger,并生成API文档。Swagger不仅可以帮助你自动生成文档,还可以提供一个交互式的UI界面,方便开发者测试和调试API。