SpringBoot中使用swagger

本文介绍如何配置并使用Swagger生成RESTful API文档。包括Swagger依赖添加、配置类编写及控制器中注解的应用,展示了如何组织API文档、分组及参数描述。

集成

//版本号
<properties>
    <springfox.swagger.version>2.9.2</springfox.swagger.version>
</properties>
    
//添加依赖
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${springfox.swagger.version}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${springfox.swagger.version}</version>
</dependency>

swagger配置项

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;

/**
 * swagger配置
 *
 * 与Application.java同级或通过@Import导入配置
 *
 * 访问地址=>http://host:port/swagger-ui.html
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean(value = "swagger模块的接口")
    public Docket apiSwagger() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())//添加接口文档页面信息
                .groupName("swagger接口")//分组名
                .select()
                .apis(RequestHandlerSelectors.basePackage("sb.simple.swagger"))//分组api所属位置
                .paths(PathSelectors.any())
                .build();
    }

    @Bean(value = "wrapper模块的接口")
    public Docket apiWrapper() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("wrapper接口")
                .select()
                .apis(RequestHandlerSelectors.basePackage("sb.simple.wrapper"))
                .paths(PathSelectors.any())
                .build();
    }
    

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("卫宁物联网数据平台服务接口文档")
                .description("接口由swagger注解生成")
                //.termsOfServiceUrl("")
                .contact("winning health")
                .version("1.0")
                .build();
    }
}

类(Controller)中使用swagger相关注解

import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("swaggerA")
@Api(value = "分组A=若未定义tags则value值用作于分组,一般设为api path=>/swaggerA", tags = "分组A", description = "详细描述但已废弃")
public class SwaggerAController {

    @GetMapping("hello")
    //httpMethod可选值=>"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"
    //code=>默认200
    @ApiOperation(value = "简要说明", notes = "详细说明", httpMethod = "GET", code = 200)
    @ApiImplicitParams({//对单一参数进行注解
            //@ApiImplicitParam(name = "参数名称", value = "参数说明", required = true, dataType = "参数类型=>String, int, boolean, 类名等", paramType = "参数的请求类型=>path, query, body, header, form"),
            @ApiImplicitParam(name = "name", value = "名字", required = true, dataType = "String", paramType = "query")
    })
    @ApiResponses({//描述可能返回的结果
            @ApiResponse(code = 200, message = "易于理解的描述", response = String.class, responseContainer = "返回的容器类型=>List, Set, Map其他值会被忽略"),
    })
    public String hello(String name) {
        return "hello:" + name;
    }

    @PostMapping("hi")
    //@ApiParam对参数进行简短的说明
    public String hi(@ApiParam(value = "姓名", required = true) String username) {
        return "hi:" + username;
    }
}

mode&Controller使用swagger注解

//model
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
@ApiModel(value = "Swagger对象", description = "model的详细描述")
public class Swagger {

    //example=>示例值
    @ApiModelProperty(value = "用户id", example = "9527", required = true)
    private int id;
    @ApiModelProperty(value = "用户名", example = "akali", required = true)
    private String name;
    @ApiModelProperty(value = "用户年龄", example = "20", required = true)
    private int age;
}

//controller
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("swaggerB")
@Api(value = "/swaggerB", tags = "分组B")
public class SwaggerBController {

    @GetMapping("hi")
    @ApiOperation(value = "打招呼", notes = "对传入的对象进行打印", httpMethod = "GET", code = 200)
    public String hi(Swagger swagger) {
        return "hello, id:" + swagger.getId() + ", name:" + swagger.getName() + ", age:" + swagger.getAge();
    }

    @PostMapping("hello")
    @ApiOperation(value = "打招呼", notes = "对传入的对象进行打印", httpMethod = "POST", code = 200)
    public String hello(Swagger swagger) {
        return "hello, id:" + swagger.getId() + ", name:" + swagger.getName() + ", age:" + swagger.getAge();
    }
}

效果展示
在这里插入图片描述

使用笔记

Long型参数接收不到

使用swagger页面测试时,Long型入参接收不到,但使用其他如postman可以接收

添加paramType="query"或"path",添加dataType="Long"
<think>好的,我现在需要在Spring Boot 3.2.4中集成和使用Swagger。之前对Swagger有些了解,但可能版本不同配置会有变化,特别是Spring Boot 3.x可能需要不同的方法。先回忆一下之前的知识,比如在Spring Boot 2.x中,通常使用springfox-swagger2和springfox-swagger-ui依赖,然后通过配置类启用Swagger。但根据用户提供的引用内容,特别是引用[2]提到Spring Boot 3使用Springdoc-OpenAPI,而引用[5]也提到Swagger2用于接口文档生成。可能需要确认Spring Boot 3.2.4是否仍然支持springfox或者需要切换到Springdoc。 查看用户提供的引用,引用[2]明确提到“SpringBoot3使用Swagger3”,并且需要配置springdoc相关属性。引用[4]和[5]是关于Spring Boot 2.x中使用springfox的例子。因此,现在Spring Boot 3.x应该使用Springdoc-OpenAPI而不是springfox。因为Springdoc是支持OpenAPI 3的,而springfox可能不再兼容新版本Spring Boot。 接下来,步骤应该是: 1. 添加Springdoc-OpenAPI的依赖。根据引用[2],可能需要引springdoc-openapi-starter-webmvc-ui。 2. 配置application.yml或properties文件,设置Swagger UI的路径等。 3. 可能不需要写配置类,因为Spring Boot 3.x可能已经自动化配置,但可能需要通过注解启用。 4. 使用Swagger的注解在Controller中描述API。 需要检查是否需要@EnableSwagger2这样的注解,或者是否已经被替代。根据引用[3],在Spring Boot 2.x中使用的是@EnableSwagger2,但Springdoc可能使用不同的注解,比如@OpenAPIDefinition。 另外,引用[2]中的配置示例是设置springdoc.swagger-ui.path,所以在application.yml中配置这个属性。可能还需要其他属性,比如API的基本信息,这可能需要通过配置类或者application.yml中的springdoc配置。 现在需要确认具体步骤: - 添加正确的依赖:在pom.xml中添加Springdoc的依赖,而不是springfox。 - 配置application.yml中的springdoc相关属性。 - 创建OpenAPI的配置类,使用@OpenAPIDefinition或@Bean来定义API信息。 - 在Controller中使用注解如@Operation、@ApiResponse等描述接口- 访问Swagger UI页面,确认是否生效。 可能的依赖是: ```xml <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.3.0</version> </dependency> ``` 版本可能需要查找最新的兼容Spring Boot 3.2.4的版本。比如,Spring Boot 3.2.x可能对应Springdoc 2.x版本。 配置类可能如下: ```java @Configuration @OpenAPIDefinition(info = @Info(title = "API文档", version = "1.0", description = "项目接口文档")) public class OpenApiConfig { } ``` 或者在application.yml中配置: ```yaml springdoc: swagger-ui: path: /swagger-ui.html api-docs: path: /v3/api-docs info: title: API文档 version: 1.0.0 description: 项目接口文档 ``` 然后,在Controller的方法上使用注解: ```java @Operation(summary = "获取用户信息", description = "根据ID查询用户") @GetMapping("/user/{id}") public User getUser(@PathVariable Long id) { // ... } ``` 这样,访问/swagger-ui.html应该可以看到生成的文档。 需要注意的是,Spring Boot 3.2.4可能对路径有变化,或者需要额外的安全配置,比如如果项目有Spring Security,需要放行Swagger相关的路径。 总结步骤: 1. 添加Springdoc依赖。 2. 配置application.yml中的springdoc属性。 3. 可选地创建配置类定义API信息。 4. 使用注解描述接口。 5. 测试访问Swagger UI。 需要验证是否所有步骤正确,特别是依赖版本是否正确,配置路径是否被正确识别,以及是否需要在SecurityConfig中允许访问相关端点。</think>### 在 Spring Boot 3.2.4 中集成 Swagger 的步骤 #### 1. 添加依赖 Spring Boot 3.x 需使用 **Springdoc-OpenAPI**(替代旧版 Springfox),在 `pom.xml` 中添加以下依赖: ```xml <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.3.0</version> <!-- 版本需与Spring Boot兼容 --> </dependency> ``` #### 2. 配置 Swagger 基本数 在 `application.yml` 或 `application.properties` 中配置 Swagger UI 路径和接口文档信息: ```yaml springdoc: swagger-ui: path: /swagger-ui.html # Swagger UI访问路径 tags-sorter: alpha # 接口标签按字母排序 api-docs: path: /v3/api-docs # OpenAPI描述文件路径 info: title: 项目接口文档 version: 1.0.0 description: Spring Boot 3.2.4集成Swagger示例 ``` #### 3. 可选:自定义 OpenAPI 配置类 若需更详细配置(如添加全局鉴权),可创建配置类: ```java import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class OpenApiConfig { @Bean public OpenAPI customOpenAPI() { return new OpenAPI() .info(new Info() .title("API文档") .version("1.0") .description("详细接口说明")); } } ``` #### 4. 在 Controller 中添加注解 使用 Swagger 注解描述接口数: ```java import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.responses.ApiResponse; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api") public class UserController { @Operation(summary = "获取用户信息", description = "根据用户ID查询详情") @ApiResponse(responseCode = "200", description = "成功回用户数据") @GetMapping("/user/{id}") public User getUser(@PathVariable Long id) { // 业务逻辑 } } ``` #### 5. 访问 Swagger UI 启动应用后,通过以下路径访问: - **Swagger UI 页面**:`http://localhost:8080/swagger-ui.html` - **OpenAPI JSON 描述文件**:`http://localhost:8080/v3/api-docs` #### 6. 安全配置(若启用 Spring Security) 若项目集成 Spring Security,需放行 Swagger 相关端点: ```java import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(auth -> auth .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll() .anyRequest().authenticated() ); return http.build(); } ``` ### 注解说明 | 注解 | 用途 | 示例 | |---------------------|--------------------------|---------------------------------------| | `@Operation` | 描述接口功能 | `@Operation(summary = "创建用户")` | | `@Parameter` | 描述接口数 | `@Parameter(name = "id", required = true)` | | `@ApiResponse` | 定义响应状态码和描述 | `@ApiResponse(responseCode = "404", description = "用户不存在")` | | `@Tag` | 分组接口(替代旧版@Api) | `@Tag(name = "用户管理")` | ### 注意事项 1. **版本兼容性**:确保 `springdoc-openapi` 版本与 Spring Boot 3.2.4 兼容(推荐查阅[官方文档](https://springdoc.org/))。 2. **生产环境禁用**:通过配置 `springdoc.swagger-ui.enabled=false` 关闭 Swagger UI[^2]。 3. **接口扫描范围**:默认扫描所有 Controller,可通过 `@Hidden` 注解隐藏特定接口
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值