为了在 Spring Boot 项目中使用 Swagger2 来生成和展示 API 文档,首先需要在项目的 pom.xml 文件中添加相应的依赖。这里我们选择 Swagger2 版本 2.2.2,因为它被证明是稳定且用户界面友好的版本。
<dependencies> <!-- Swagger2 核心库 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency> <!-- Swagger2 UI 界面库 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> </dependency> </dependencies>
注意事项
- 版本选择:虽然可能存在更高版本的 Swagger2,但根据实际经验,2.2.2 版本在稳定性和用户体验方面表现良好,因此推荐使用该版本。
- 兼容性检查:确保所选版本与你的 Spring Boot 版本兼容。一般来说,Spring Boot 2.x 版本系列与 Swagger2 2.2.2 版本是兼容的。
- 更新 Maven 项目:添加完依赖后,记得刷新或更新你的 Maven 项目以下载这些依赖项。
创建 Swagger 配置类
接下来,在你的 Spring Boot 应用程序中创建一个配置类来启用 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.service.ApiInfo; 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 createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() // 指定扫描的包路径,生成对应的API接口文档 .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot 使用 Swagger2 构建 RESTful APIs") .description("更多 Spring Boot 相关文章请访问:https://spring.io/projects/spring-boot") .version("1.0") .build(); } }
关键点解释
- @EnableSwagger2:启用 Swagger2 功能。
- Docket:构建 Swagger 文档的核心对象,通过
.select()方法指定要扫描的包路径。 - ApiInfo:用于定义 API 文档的基本信息,如标题、描述和版本号等。
访问 Swagger UI
完成上述配置后,启动你的 Spring Boot 应用程序,并通过浏览器访问以下地址查看 Swagger UI 页面:
http://localhost:8080/swagger-ui.html
在这里,你可以看到所有已配置的 API 接口,并能够直接在页面上进行测试。
生产环境中的注意事项
在生产环境中,出于安全考虑,通常不希望暴露 Swagger UI。可以通过条件配置来禁用它:
@Bean public Docket createRestApi() { boolean swaggerEnabled = Boolean.parseBoolean(System.getenv().getOrDefault("SWAGGER_ENABLED", "false")); return new Docket(DocumentationType.SWAGGER_2) .enable(swaggerEnabled) // 控制是否启用 Swagger ... }
并在 application-prod.yml 中设置:
swagger: enabled: false
这样,在生产环境下 Swagger 将不会被启用,从而提高了安全性。