springboot集成Swagger 3.0

本文介绍了如何在SpringBoot项目中集成Swagger 3.0,包括添加依赖、启用Swagger、配置接口文档以及常用注解的使用。通过实例演示了如何为API和参数提供详细说明,帮助开发者更好地理解和使用Swagger进行接口文档生成和测试。

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

Swagger介绍

Swagger 是一个用于生成、描述和调用 RESTful 接口的 Web 服务。通俗的来讲,Swagger 就是将项目中所有(想要暴露的)接口展现在页面上,并且可以进行接口调用和测试的服务。

添加依赖

			<dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-boot-starter</artifactId>
                <version>3.0.0</version>
            </dependency>

开启swagger

在springboot的启动类型添加注解 @EnableOpenApi

@SpringBootApplication
@EnableOpenApi
public class ProjectTestUserApplication {

    public static void main(String[] args) {
        SpringApplication.run(ProjectTestUserApplication.class, args);
    }

}

配置

package com.example.user.Utils;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.user.controller"))
                .build();
    }
}

访问swagger

直接访问http://ip:端口/swagger-ui/

swagger 常用注解

  1. @Api 类注解,在控制类添加此注解,可以对控制器类进行功能说明
  2. @ApiOperation 方法注解:说明接口方法的作用
  3. @ApiImplicitParams和@ApiImplicitParam 在 Rest 接口方法上使用来指定请求参数
  4. @ApiParam 是注解api的参数,用于swagger提供开发者文档,文档中生成的注释内容
@RequestMapping("/userController")
@RestController
@Api(value = "用户")
public class UserController {

    @Autowired
    private UserFeign userFeign;

    /**
     * 获取参数
     * @return
     */
    @ApiOperation(value = "查询用户")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "string",name = "name",value = "用户名")
    })
    @GetMapping("userShow")
    public List<UserCommon> userShow(@ApiParam(value = "用户名",required = true) @RequestBody UserVo userCommon){
        return  userFeign.show();
    }
}

  1. @ApiIgnore 可以用在类、方法上,方法参数中,用来屏蔽某些接口或参数,使其不在页面上显示。
  2. @ApiModel 类注解,在返回和参数实体类添加此注解,可以对返回和参数实体类进行说明
  3. @ApiModelProperty 参数注解
@ApiModel("用户vo")
@Data
public class UserVo {

    private int id;

    @ApiModelProperty(value = "编号")
    private String  name;

    @ApiModelProperty(value = "年龄")
    private int age;
}

参数的详细介绍可以看此作者,写的较为详细添加链接描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值