手把手教你SpringBoot快速集成Swagger的配置过程
导语
相信大家无论是做前端还是做后端的,都被接口接口文档所折磨过,前端抱怨接口文档和后端给的不一致,后端抱怨写接口文档很麻烦,所以Swagger就诞生了。直接配置即可自动生成接口文档,而且提供了高效的API测试
话不多说直接开干
导入SpringBoot集成Swagger所需要的依赖
org.springframework.boot spring-boot-starter-web io.springfox springfox-swagger2 2.9.2 io.springfox springfox-swagger-ui 2.9.2
Swagger可视化界面可分为三个区域
Swagger相关配置
packagecom.example.config;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importspringfox.documentation.builders.RequestHandlerSelectors;
importspringfox.documentation.service.ApiInfo;
importspringfox.documentation.service.Contact;
importspringfox.documentation.spi.DocumentationType;
importspringfox.documentation.spring.web.plugins.Docket;
importspringfox.documentation.swagger2.annotations.EnableSwagger2;
importjava.util.ArrayList;
@Configuration
@EnableSwagger2//开启Swagger的使用
publicclassSwaggerConfig{
@Bean//Swagger的使用主要是要将docket对象传入IOC容器
publicDocketdocket(){
returnnewDocket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())//关于文档的各种信息
.enable(true)//使Swagger生效
.groupName("常安祖")
.select()//选择扫描的接口
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))//指定扫描的接口
.build();
}
publicApiInfoapiInfo(){
Contactcontact=newContact("长安","https://blog.csdn.net/weixin_45647685","719801748@qq.com");//个人的联系方式
returnnewApiInfo("长安的文档","长安的开发文档","1.0","urn:tos",null,"Apache2.0","http://www.apache.org/licenses/LICENSE-2.0",newArrayList());//文档的各种信息
}
}
@ApiModel()//主要用来标注返回的实体类
@ApiModelProperty()//主要用来标注实体类中的属性
案例:
@ApiModel("用户的实体类")
publicclassUserimplementsSerializable{
@ApiModelProperty("用户的id")
privateIntegerid;
@ApiModelProperty("用户的姓名")
privateStringname;
@ApiModelProperty("用户的年纪")
privateIntegerage;
publicIntegergetId(){
returnid;
}
publicUser(Integerid,Stringname,Integerage){
this.id=id;
this.name=name;
this.age=age;
}
publicvoidsetId(Integerid){
this.id=id;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicIntegergetAge(){
returnage;
}
publicvoidsetAge(Integerage){
this.age=age;
}
}
@ApiModelProperty用来标注API接口
案例:
packagecom.yangzihao.controller;
importcom.yangzihao.entity.User;
importio.swagger.annotations.ApiModelProperty;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.RequestMapping;
@RestController
publicclassUserController{
@ApiModelProperty("得到一个User")
@GetMapping("/getUser")
publicUsergetUser(){
returnnewUser(1,"测试",18);
}
}
进入Swagger可视化界面
使用Swagger进行接口测试
执行
到此这篇关于手把手教你SpringBoot快速集成Swagger的配置过程的文章就介绍到这了,更多相关SpringBoot集成Swagger内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。