Swagger 是一个开源的 API 文档工具,可以帮助开发人员自动生成 API 文档。Swagger 支持多种编程语言,包括 Java。
在 Java 中使用 Swagger,需要完成以下步骤:
使用 Swagger 可以非常方便地生成 API 文档,提高开发效率和文档的可读性。
- 添加 Swagger 依赖:在项目的 pom.xml 文件中添加 Swagger 依赖:
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${springfox.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${springfox.version}</version> </dependency>
其中,
${springfox.version}
是 Swagger 的版本号。 - 添加 Swagger 配置类:创建一个 Swagger 配置类,用于配置 Swagger:
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("My API") .description("My API Description") .version("1.0.0") .build(); } }
在这个配置类中,我们创建了一个
Docket
对象,用于配置 Swagger。RequestHandlerSelectors
用于指定 API 文档生成的基础包路径,PathSelectors
用于指定生成哪些 API 接口的文档。 -
添加 Swagger 注解:在 API 接口方法中,添加 Swagger 相关的注解,例如
@ApiOperation
、@ApiParam
等。这些注解用于描述接口的基本信息、请求参数、响应参数等等。 -
启动应用程序:在启动应用程序后,访问 Swagger UI 页面即可查看自动生成的 API 文档。Swagger UI 页面的地址为
http://localhost:port/swagger-ui.html
,其中port
是应用程序的端口号。