SpringBoot整合Swagger2,代码文档一手抓
    		       		warning:
    		            这篇文章距离上次修改已过429天,其中的内容可能已经有所变动。
    		        
        		                
                要在Spring Boot项目中整合Swagger2,你需要按照以下步骤操作:
- 添加Swagger2依赖到你的pom.xml文件中:
<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>- 创建一个Swagger2配置类,如SwaggerConfig.java:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.any())
                .paths(PathSelectors.any())
                .build();
    }
}- 在你的Spring Boot应用主类或者配置类上添加@EnableSwagger2注解。
- 在你的控制器类或方法上使用Swagger注解来描述API。
例如,一个简单的REST控制器,它使用Swagger注解:
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
 
@RestController
@Api(value = "用户管理", tags = {"用户操作接口"})
public class UserController {
 
    @ApiOperation(value = "获取用户信息", notes = "根据用户ID获取用户信息")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 404, message = "未找到用户")
    })
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path")
    @GetMapping("/users/{id}")
    public String getUserById(@PathVariable Long id) {
        // 实现省略
        return "User " + id;
    }
}- 启动Spring Boot应用,然后在浏览器中访问http://<host>:<port>/swagger-ui.html来查看Swagger生成的API文档。
确保你的Spring Boot应用配置了对应的端口和上下文路径,这样Swagger UI才能正确显示。如果你使用的是Spring Boot 2.x版本,可能需要将Swagger的版本更新到最新兼容的版本。
评论已关闭