-
前言
-
1.SpringBoot引入项目依赖:
-
2.启动swagger并且添加配置:
-
3.接口注解定义:
-
4.泛型返回类注解定义:
-
5.swagger2效果:
-
6.swagger集成yapi:
-
总结
前言
现在几乎项目接口文档都是使用的Swagger去管理,因为Swagger集成项目定义api非常的方便所有很受好评,Swagger还可以集成yapi直接配置好之后就可以进行接口信息同步过去。本篇结合我项目当中的使用基于SpringBoot进行一个总结。
1.SpringBoot引入项目依赖:
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
我的SpringBoot版本使用的是接近于最新的版本:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
2.启动swagger并且添加配置:
启动swagger的注解是:EnableSwagger2 上配置源码:
@Configuration
@EnableSwagger2
//@Profile({"dev","test"})
public class SwaggerApp {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
//控制开关
// .enable()
.apiInfo(apiInfo())
.select()
//为当前包路径
.apis(RequestHandlerSelectors.basePackage("com.xj.show.sw.controller"))
.paths(PathSelectors.any())
.build();
// return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).build();
}
//构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title("Spring Boot 使用 Swagger2 构建RESTful API")
//创建人
.contact(new Contact("my web", "http://www.our666.com/", ""))
//版本号
.version("1.0")
//描述
.description("API 描述")
.build();
}
}
上面就是配置的信息,已经实战过没问题,有两处需要注意的地方。
-
1.@Profile({“dev”,”test”})注意生产环境一般不开启swagger -
2.RequestHandlerSelectors.basePackage必须配置正确接口文档才能显示出来
3.接口注解定义:
先上源码:
@RestController
@Api(value = "用户接口",description = "用户接口实现")
public class UserController {
@ApiOperation(value = "获取用户信息",notes = "标记信息")
@PostMapping("/findUser")
public ApiReturn<FindUserResult> findUser(@RequestBody FindUserArg arg){
上线就是配置了接口类和接口定义的方法。涉及到的实体类的swagger注解:
public class FindUserArg {
@ApiModelProperty("参数age")
private int age;
}
4.泛型返回类注解定义:
@ApiModelProperty(value = "返回的数据", name = "data", dataType = "t")
private T data;
这块是比较重要的一个摸索,经过实战才搞定的泛型类的展示实体类的注释的地方。
5.swagger2效果:
启动SpringBoot以后访问地址:http://localhost:8899/swagger-ui.html
效果展示1:效果展示2:
上面就是整个swagger2配置完以后的效果图了。
6.swagger集成yapi:
配置图:上面就是yapi中配置swagger地址的图,一般就是同步测试环境的地址,做到每隔2分钟进行一个同步的操作。
总结
上面就是完整的整个的Swagger的使用过程,其中提到了一些使用的技巧,贯穿了整个现在大公司的使用流程和集成yapi的方法,希望能帮助到大家,如果你想跟我有更多的交流,欢迎关注我的头条号和微信公众号:Java时间屋 期待你的到来。
原文始发于微信公众号(Java时间屋):59.java中Swagger高级使用技巧
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/251811.html