springboot中使用swagger

本文介绍如何在Spring Boot项目中使用Swagger2快速生成RESTful API文档,包括Maven坐标配置、Swagger配置类编写、注解使用及访问地址说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

maven坐标:

<!--swagger-->
<dependency>
	<groupId>com.spring4all</groupId>
	<artifactId>swagger-spring-boot-starter</artifactId>
	<version>1.7.1.RELEASE</version>
</dependency>

配置类:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    public static final String VERSION = "1.0.0";

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))//api接口包扫描路径
                .paths(PathSelectors.any())//可以根据url路径设置哪些请求加入文档,忽略哪些请求
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SmartItApp后台接口文档")//设置文档的标题
                .description("详细接口内容请找开发人员确定")//设置文档的描述->1.Overview
                .version(VERSION)//设置文档的版本信息-> 1.1 Version information
                .build();
    }
}

使用的注解:

@Api("告警模块") //修饰类

@ApiOperation(value = "方法描述",produces = "application/json") //修饰方法

@ApiImplicitParams({  //入参描述
	@ApiImplicitParam(name="username",value = "用户名 必传",dataType = "String"),
	@ApiImplicitParam(name="password",value = "密码 必传",dataType = "String")
})

@ApiModel(value = "User",description = "用户名")  //入参实体类描述,放在类上
@ApiModelProperty(value = "请求的页大小 必传",dataType = "Integer",example = "5")  //入参字段描述,放在字段上

访问地址:

http://localhost:8080/swagger-ui.html#/

<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、付费专栏及课程。

余额充值