swagger的入门教程

本文档将引导你入门Swagger2,通过在SpringBoot项目中配置相关依赖和注解,实现API接口的文档化。首先,需要在POM文件引入Swagger2依赖,并创建Swagger2Config配置类,启用Swagger2功能。接着,在启动类上指定扫描包,以便Swagger能发现相关API。启动应用后,访问`swagger-ui.html`页面即可查看接口文档。常用注解包括用于实体类、控制器和方法参数的注解。

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

一. 创建一个swagger

1.springboot的pom.xml中导入依赖:

		<!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
        </dependency>
        <!--swagger ui-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
        </dependency>

2.在config包下,创建Swagger2Config类:
两个注解非常重要:@Configuration和EnableSwagger2

@Configuration  //配置类
@EnableSwagger2  //swagger注解
public class Swagger2Config {
    @Bean
    public Docket adminApiConfig(){
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("adminApi")
                .apiInfo(adminApiInfo())
                .select()
                //直线admin路径下的也页面
                .paths(Predicates.and(PathSelectors.regex("/admin/.*")))
                .build();
    }

    private ApiInfo adminApiInfo(){
        return new ApiInfoBuilder()
                .title("xxx后台管理系统——API文档")
                .description("本文档描述了xxx后台管理系统接口")
                .version("1.0")
                .contact(new Contact("作者名字","url","联系方式(邮箱)"))
                .build();
    }

}

3.在springboot启动类上添加扫描包,扫描包含config的路径:

@SpringBootApplication
@ComponentScan({"com.xxx"})
public class ServiceCoreApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServiceCoreApplication.class, args);
    }
}

4.启动服务器查看文档接口:
http://localhost:8080/swagger-ui.html
在这里插入图片描述

二. 常用注解:

1.实体类注解:pojo实体类中可以添加一些自定义设置,例如:

@ApiModelProperty(value = "创建时间", example = "2019-01-01 8:00:00")
private LocalDateTime createTime;

2.controller注解:
定义在类上:

@Api(tags="积分管理")

定义在方法上:


@ApiOperator("积分等级列表")
@GetRequest("/list")
public List<Entity> list(){}

@ApiOperator(value="根据id删除积分等级",notes="逻辑删除")
@DeleteRequest("/delete/{}")
public void delete(@PathVariable Integer id){}

定义在参数上:

public void delete(@PathVariable 
@ApiParam(value="数据id",required= true, example="100")
Integer id){}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

借一缕月光

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值