Java项目集成Swagger可自动生成API文档,提升开发效率。1. Spring Boot 2.x可使用Springfox,需添加依赖并配置@EnableSwagger2及Docket Bean,访问/swagger-ui.html查看文档;2. Spring Boot 3+推荐使用SpringDoc,引入springdoc-openapi-starter-webmvc-ui依赖即可自动集成,无需额外配置,访问/swagger-ui/index.html;3. 通过@Tag、@Operation、@Parameter等注解丰富接口描述;4. 生产环境应关闭swagger-ui和api-docs,支持安全认证展示与中文文档。新项目建议优先选用SpringDoc,兼容性好、集成简单。

Java项目中集成Swagger可以快速实现API文档的自动生成,提升开发效率,减少手动编写文档的工作量。目前主流使用的是Spring Boot项目结合Swagger(通常使用Springfox或SpringDoc)来自动生成接口文档。
Springfox是较早流行的Swagger集成工具,适用于Spring Boot 2.x版本。
步骤如下:pom.xml中引入Springfox Swagger依赖:
<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>
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("项目API文档")
.description("基于Swagger生成的RESTful API文档")
.version("1.0")
.build();
}
}
Spring Boot 3以后不再兼容Springfox,推荐使用SpringDoc OpenAPI,它支持OpenAPI 3规范,且无需额外配置即可自动集成。
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.0.2</version>
</dependency>
通过在Controller和方法上添加Swagger注解,可以让文档更清晰。
立即学习“Java免费学习笔记(深入)”;
@Tag(name = "用户模块"):给Controller分类@Operation(summary = "获取用户信息", description = "根据ID查询用户"):描述接口功能@Parameter(description = "用户ID", required = true):描述参数@ApiResponse:定义响应状态码和说明示例:
@RestController
@Tag(name = "用户管理")
public class UserController {
@GetMapping("/user/{id}")
@Operation(summary = "获取用户详情")
public ResponseEntity<User> getUserById(
@Parameter(description = "用户ID", required = true)
@PathVariable Long id) {
// 业务逻辑
return ResponseEntity.ok(new User(id, "张三"));
}
}
springdoc:
api-docs:
enabled: false
swagger-ui:
enabled: false
基本上就这些。选择Springfox还是SpringDoc取决于你的Spring Boot版本。新项目建议直接使用SpringDoc,更轻量、兼容性更好,集成也更简单。
以上就是java怎么集成Swagger生成API文档 使用Swagger自动生成接口文档的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号