Swagger
Swagger即API接口管理工具。
在前后端分离的项目中,前端和后台的项目时分开的,而前后端通过API来交互。二者相对独立(松耦合)。
但是,如果前后端没有能够即使更新二者的需求,就会导致二者结合失败,故而影响开发效率。
而Swagger能够实现API文档与API的定义同步更新。
官网:https://swagger.io/
SpringBoot整合Swagger
-
创建SpringBoot项目
-
导入依赖
<!-- Swagger2依赖 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
-
创建Controller
随意创建访问路径。
-
创建配置类
配置类需要注入一个Docket的Bean。
@Configuration //让Spring来加载该类配置。 @EnableSwagger2 //启用Swagger2 class Swagger2 { @Bean public Docket createRestApi(Environment e) { // 获取开发环境 Profiles env = Profiles.of("dev", "test"); boolean flag = e.acceptsProfiles(env); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) //创建该Api的基本信息(这些基本信息会展现在文档页面中) .groupName("组1") // 多个开发组可以扫描自己的包,并只显示自己的组的API .enable(flag) // 根据开发环境判断是否显示swagger .select() .apis(RequestHandlerSelectors.basePackage("com.zjj.swagger01.controller")) //指定要扫描的包 .paths(PathSelectors.any()) // 扫描过滤 .build() ; } private ApiInfo apiInfo() { // 依据项目进行修改 Contact contact = new Contact("zjj","123abc.com","123abc@xxx.com"); return new ApiInfoBuilder() .title("Swagger学习记录") .description("2021.8.10") .contact(contact) .version("1.0") .build(); } }
可以根据具体的生产环境设置其是否显示swagger。具体操作为获取当前的生产环境,并传入enable()中。
访问:http://localhost:8080/swagger-ui.html
常用注解
使用注解为接口的类、方法、参数编写注释。
@Api
作用在类上,说明该类的作用。
主要参数:
- value:url的路径
- tags:类的描述,设置该值会覆盖value
例如:
@Api(tags = {"用户controller"})
@ApiOperation
作用在方法上,说明该方法的做用。
主要参数:
- value:简要描述
- notes:详细描述
- response:返回对象
例如:
@ApiOperation(value = "查询用户信息", notes = "随机返回一个用户的信息")
@ApiParam
作用于请求参数,对请求参数的解释。
主要参数:
- name:参数名称
- value:参数值
- required:是否必须
- defaultValue:默认值
例如:
public User getUser(@ApiParam(name = "userId",value = "用户id", required = true, defaultValue = "1") Integer id){
@ApiResponses和@ApiResponse
作用在方法上,用于解释响应码的意义
主要参数:
- code:响应码
- message:描述
例如:
@ApiResponses({
@ApiResponse(code = 400, message = "请求不存在"),
@ApiResponse(code = 500, message = "服务器异常")
})
@ApiModel
作用在实体类上,对实体类的表述。
主要参数:
- value:模型简介
- description:详细介绍
例如:
@ApiModel(value = "用户实体类")
@ApiModelProperty
作用在实体类的属性上,描述属性的意义。
主要参数:
- name:属性名称
- value:属性解释
- datatype:属性类型
例如:
@ApiModelProperty(value = "用户名" ,name = "userName", dataType = "String")