Spring Boot 集成 Swagger

本文详细介绍如何在SpringBoot项目中集成Swagger2,包括添加依赖、配置Swagger、控制器注解及实体类注解,最后通过访问Swagger-UI页面查看API文档。

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

1、添加依赖。

<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>

2、添加 Swagger 配置。

@Configuration
@EnableSwagger2
@Profile({"dev", "test"})
public class Swagger2Config {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .directModelSubstitute(Date.class, Long.class) // 日期使用时间戳
                .globalOperationParameters(setSession())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.test.aggregate.server.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("com.test.aggregate.server服务api")
                .version("1.0")
                .build();
    }

    /**
     * 设置header和session
     * */
    private List<Parameter> setSession() {
        List<Parameter> parameters = new ArrayList<>();
        ParameterBuilder builder = new ParameterBuilder();
        builder.name(RequestInfo.USER_ID_NAME)
                .description("用户id")
                .modelRef(new ModelRef("string"))
                .parameterType("session")
                .required(false)
                .build();
        parameters.add(builder.build());

        return parameters;
    }
}

说明:

(1).apis() 设置需要扫描的 controller 包路径。

(2).paths()  可以设置筛选 API 的 url 进行过滤。

(3)setSession() 方法用于设置通过 swagger 请求时,携带的cookie/session。主要为了鉴权方便用。

3、controller 类, 添加注解。

@Api(value = "demo请求接口", tags = "demo请求接口")
public interface DemoApi {
    @ApiOperation(value = "demo", notes = "demo")
    @GetMapping(value = "/v1/agg/demo")
    DeferredResult<Result<DemoOVO>> queryDemo(@ApiParam(name = "userId", value = "用户id", required = true) @RequestParam(name = "userId") Long userId,
                                              @ApiParam(name = "roleIds", value = "归属的角色id列表", required = true) @RequestParam(name = "roleIds") List<Long> roleIds);
}

说明:

(1)如果想在 swagger 文档中,屏蔽掉某个接口,可以在接口上添加 @ApiIgnore 注解。

4、请求/应答实体,添加注解。

/**
 * demo应答
 */
@Data
@ApiModel(value = "demo应答")
public class DemoOVO {
    /**
     * 用户id
     */
    @ApiModelProperty(value = "用户id")
    private Long userId;
    /**
     * 用户名
     */
    @ApiModelProperty(value = "用户名")
    private String userName;
    /**
     * 性别
     */
    @ApiModelProperty(value = "性别")
    private String sex;
    /**
     * 年龄
     */
    @ApiModelProperty(value = "年龄")
    private int age;

}

5、启动项目,访问

http://ip:port/swagger-ui.html

一起学习

### Spring Boot 整合 Swagger 实现 API 文档自动化配置 #### 添加依赖项 为了使 Spring Boot 项目能够支持 Swagger 自动生成 API 文档,在项目的 `pom.xml` 文件中需引入相应的 Maven 依赖: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> ``` 此操作确保了 spring-boot-starter-swagger 成为 Spring Boot 生态系统的一部分,实现了与框架的无缝集成并提供快速开发能力[^1]。 #### 配置Swagger属性 接着定义 Swagger 的基本设置。可以在 application.properties 或者 application.yml 中加入如下配置来定制化 Swagger 行为: 对于 properties 文件: ```properties springdoc.api-docs.path=/v3/api-docs springdoc.swagger-ui.path=/swagger-ui.html ``` 对于 YAML 文件: ```yaml springdoc: api-docs: path: /v3/api-docs swagger-ui: path: /swagger-ui.html ``` 这些路径指定了 OpenAPI 描述文件的位置以及 Swagger UI 访问地址[^2]。 #### 创建Swagger配置类 (可选) 如果希望进一步调整 Swagger 设置,则可以创建一个新的 Java 类用于配置 Swagger 特定选项。下面是一个简单的例子展示如何通过此类启用或禁用某些特性: ```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; @Configuration public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.OAS_30) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } } ``` 这段代码片段展示了怎样构建一个基于 OAS 3.0 规范的 Docket 对象,并将其应用于整个应用程序中的所有控制器方法上。 完成上述步骤之后,当启动 Spring Boot 应用程序时,就可以通过访问指定 URL 来查看由 Knife4j 提供的增强版 Swagger UI 页面,从而方便地管理和测试 RESTful Web Services 接口。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

magic_kid_2010

你的支持将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值