springboot整合Swagger——接口测试

本文分享了一位开发者从使用Postman遇到的挫折转向配置并使用Swagger进行API文档测试的经历。通过详细步骤介绍了如何在项目中引入Swagger,并在Controller中添加必要的注解以实现接口文档的自动生成。

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

一把辛酸泪

自己刚开始使用postman测试接口,使用不方便算了,而且还不听话,还浪费了我大半天的时间,明明我的接口没毛病,它报400,我以为是自己接口写的有问题,类型不对呢。总之别用postman,感谢同事的帮助。
于是我我配置swagger,使用swagger测试。

步骤

1.首先在pom文件中引入

    <!--引入swagger相关配置-->
    <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-annotations</artifactId>
        <version>1.5.20</version>
    </dependency>
    
    <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.添加相应swagger2类

package com.imooc.product.config;

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;

@Configuration
@EnableSwagger2
public class Swagger2 {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.imooc.product.controller"))
                .paths(PathSelectors.any()).build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("Springboot-api文档")
                .description("").termsOfServiceUrl("")
                .version("1.0").build();
    }

}

// 注意:"com.imooc.product.controller" 指的是你的controller包路径

如图:
在这里插入图片描述
3.添加注解响应controller里面加注解

  1. @Api注解:添加到类上

在这里插入图片描述

  1. @ApiOperation:用在方法上

在这里插入图片描述
4.配置idea启动页面
在这里插入图片描述
5.一切正常,自己的接口也没有毛病
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值