SpringBoot整合Swagger2快速指南

Swagger简介

Swagger是一款强大的API文档生成工具,它能够自动为RESTful API生成可视化文档,支持在线测试接口,极大提高了前后端协作效率。本文将详细介绍如何在SpringBoot项目中整合Swagger2。

环境准备

版本要求

重要提示:SpringBoot版本不能过高,推荐使用2.5.6版本:


    org.springframework.boot
    spring-boot-starter-parent
    2.5.6

添加依赖



    io.springfox
    springfox-swagger-ui
    2.9.2



    io.springfox
    springfox-swagger2
    2.9.2

Swagger配置类

基础配置类

创建SwaggerConfig.java配置类:

@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
    
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .enable(true);
    }
    
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("API文档")
                .description("接口文档详情信息")
                .version("1.0")
                .contact(new Contact("开发者", "", "[email protected]"))
                .licenseUrl("")
                .build();
    }
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

配置说明

  • @EnableSwagger2:启用Swagger2功能
  • Docket:Swagger的核心配置类
  • apiInfo():设置文档的基本信息
  • addResourceHandlers():配置静态资源映射

Swagger注解详解

控制器层注解

类级别注解:

@Controller
@RequestMapping("/user")
@Api(tags = {"用户信息接口"})
public class UserController {
    // ...
}

方法级别注解:

@Controller
@RequestMapping("/user")
@Api(tags = {"用户信息接口"})
public class UserController {
    // ...
}

参数注解

简单参数:

@ApiImplicitParams({
    @ApiImplicitParam(value = "用户名", name = "userName", dataType = "string"),
    @ApiImplicitParam(value = "年龄", name = "age", dataType = "integer")
})
public List findAll(String userName, int age) {
    // ...
}

实体类参数:

@ApiModel("用户类实体信息")
public class User {
    @ApiModelProperty(value = "用户id", example = "1")
    private Integer id;
    @ApiModelProperty(value = "用户名", example = "张三")
    private String username;
    // 其他属性...
}

接口测试

启动项目后访问以下URL进入Swagger UI界面:

Swagger UIhttp://localhost:8080/swagger-ui.html界面将展示所有配置了Swagger注解的API,你可以:

  1. 查看API详细说明
  2. 直接测试接口
  3. 查看请求/响应示例

你可能感兴趣的:(SpringBoot,spring,boot,后端,java)