自动生成文档框架.
步骤:
1.集成maven依赖
2.添加配置类,制定整个文档的署名,介绍等信息
3.编写接口类,视图实体类,结果映射类
4.启动项目,访问本地地址+端口+/doc.html(http://localhost:8080/doc.html) 具体可参考knife4j-spring-ui依赖内容
5.接口访问资源(用于接口调用,以后网关对接后可以汇总所有模块的文档,访问网关做到统一的访问在线文档)
分组接口:/swagger-resources
例如:localhost:8080/swagger-resources
详情实例接口:/v2/api-docs
例如:localhost:8080/v2/api-docs?group=user-group
集成,maven依赖:
springboot版本:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
knife4j依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<!--在引用时请在maven*仓库搜索最新版本号-->
<version>2.0.8</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
配置类:
package com.example.springbootknife4j.config;
import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
/**
* 通过配置类整合Swagger2
*
* @author 发哥讲Java
* @version 1.0
* @date 2021-05-30 15:28
*/
@Configuration
@EnableSwagger2WebMvc
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfiguration {
/**
* 注解使用:
*
* @Api(tags = {“测试Controller”}) 给controller 起别名 类注解
* @ApiOperation(“测试demo”) 方法的描述
* @ApiIgnore 忽略 标注方法 或者 参数 则不生成对应文档
* @ApiImplicitParams
* @ApiImplicitParam 俩个配合使用
* @ApiModel(value = “User”,description = “用户实体”) 标注于实体类
* @ApiModelProperty(value = “主键”,name = “id”) 标注与实体类的属性
* ----------------
* @ApiOperationSupport(author = “lsx”,order = 1) 标注方法上 添加作者 接口排序(Knife4j增强注解:
* 需要在application.yml中开启增强功能)
* ----------------
*
* ———————建议不使用—————————
* @ApiParam(name = “a”,value = “用户名”,required = true) 对参数的描述
*/
@Bean
public Docket swagger2ConfigDefault() {
return new Docket(DocumentationType.SWAGGER_2) //选择swagger类型
.apiInfo(getApiInfo("用户中心", "用户中心的接口文档,关于用户的操作都是这个模块里面"))
.groupName("user-group")//分组的名称
.select() // 选择器
//方式一: 配置扫描 所有想在swagger界面的统一管理接口。都必须在此包下
.apis(RequestHandlerSelectors.basePackage("com.example.springbootknife4j.controller"))
//方式二: 只有当方法上有 @ApiOperation 注解时才能生成对应的接口文档
//.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any()) // 指定路径范围 这里表示所有路径
.build(); // 构建swagger文档对象
}
private ApiInfo getApiInfo(String title, String description) {
return new ApiInfoBuilder() //设置文档上下文信息
.title(title) // 文档标题
.description(description) // 简介
.version("1.0.0") // 版本
// 设置联系人 : 作者 网站地址 邮箱
.contact(new Contact("发哥讲Java", "https://gitee.com/naimaohome", "694204477@qq.com"))
// 服务条款链接
.termsOfServiceUrl("https://gitee.com/naimaohome")
// 认证许可
.license("my swagger -- test 认证许可")
// 认证许可链接
.licenseUrl("https://www.baidu.com")
.build(); // 构建上下文对象a
}
}
接口,视图实体接收类,视图实体结果返回类
1.结果返回类
package com.example.springbootknife4j;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 我还没有写描述
*
* @author <发哥讲Java-694204477@qq.com>
* @version 1.0
* @date 2021/5/30 23:25
*/
@Data
public class Result<T> implements Serializable {
@ApiModelProperty(value = "响应码", name = "code")
private String code;
@ApiModelProperty(value = "响应消息", name = "msg")
private String msg;
@ApiModelProperty(value = "响应数据", name = "data")
private T data;
public static <T> Result<T> ok(T data) {
Result<T> result = new Result<>();
result.setCode("200");
result.setMsg("success");
result.setData(data);
return result;
}
}
记住最好使用泛型,然后在接口controller中最好指定好类型,然后会自动映射出视图类,并含有注释
2.视图实体接收类
package com.example.springbootknife4j.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiParam;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
/**
* TODO
*
* @author 发哥讲Java
* @version 1.0
* @date 2021-05-30 16:51
*/
@Data
@Accessors(chain = true)
@ApiModel("用户视图接收类 - userVo")
public class UserVo {
@ApiModelProperty(value = "主键", name = "id")
private String id;
@ApiModelProperty(value = "用户名", name = "username")
private String username;
@ApiModelProperty(value = "密码", name = "password")
private String password;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@ApiModelProperty(value = "创建日期", name = "crateTime")
private Date crateTime;
}
3.视图结果实体返回类
package com.example.springbootknife4j.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* TODO
*
* @author 发哥讲Java
* @version 1.0
* @date 2021-05-30 16:51
*/
@Data
@Accessors(chain = true)
@ApiModel("用户实体类 - user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "主键", name = "id")
private String id;
@ApiModelProperty(value = "用户名", name = "username")
private String username;
@ApiModelProperty(value = "密码", name = "password")
private String password;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@ApiModelProperty(value = "创建日期", name = "crateTime")
private Date crateTime;
/**
* 扩展
*/
@ApiModelProperty(value = "课程list")
private List<Course> courseList = new ArrayList<>();
}
package com.example.springbootknife4j.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* 我还没有写描述
*
* @author <发哥讲Java-694204477@qq.com>
* @version 1.0
* @date 2021/5/30 0:35
*/
@Data
@Accessors(chain = true)
@ApiModel("课程视图类 - CourseVo")
public class Course implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "名称", name = "name")
private String name;
@ApiModelProperty(value = "课程id", name = "courseId")
private String courseId;
}
4.接口
package com.example.springbootknife4j.controller;
import com.example.springbootknife4j.Result;
import com.example.springbootknife4j.vo.Course;
import com.example.springbootknife4j.vo.User;
import com.example.springbootknife4j.vo.UserVo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
import java.util.Collections;
import java.util.UUID;
/**
* TODO
*
* @author 发哥讲Java
* @version 1.0
* @date 2021-05-30 15:12
*/
@RestController
// 给整个类定义 tags, 将所有接口归档当前tags(菜单)下
// 给controller 起别名 类注解
@Api(tags = "测试API类 - hello")
public class HelloController {
// 方法的描述,
@GetMapping("/hello")
@ApiOperation(value = "访问hello接口")
@ApiOperationSupport(author = "发哥讲Java")//标注作者
@ApiImplicitParams(value = {
@ApiImplicitParam(name = "name", value = "姓名"),
@ApiImplicitParam(name = "age", value = "年龄"),
})
public Result<String> hello(String name, Integer age) {
System.out.println("name = " + name);
System.out.println("age = " + age);
return Result.ok(name + "--" + age);
}
// 方法的描述,
@GetMapping("/helloVo")
@ApiOperation(value = "访问复杂参数-hello接口")
@ApiOperationSupport(author = "发哥讲Java")//标注作者
public Result<String> helloVo(UserVo userVo) {
System.out.println("userVo = " + userVo);
return Result.ok(userVo.toString());
}
@PostMapping("/post")
@ApiOperation("复杂post请求接口")
@ApiOperationSupport(author = "发哥讲Java")//标注作者
public Result<User> postMapping(@RequestBody UserVo userVo) {
// 构建user
User user = new User();
user.setId(UUID.randomUUID().toString())
.setUsername(userVo.getUsername())
.setPassword(userVo.getPassword())
.setCrateTime(userVo.getCrateTime());
// 构建 课程list
Course courseVo = new Course();
courseVo.setCourseId(UUID.randomUUID().toString()).setName("");
user.setCourseList(Collections.singletonList(courseVo));
return Result.ok(user);
}
}
界面演示
地址:用户中心
hello接口
复杂hello接口
post接口
喜欢小编的可以关注公众号 发哥讲Java, 点击联系我,可以获取到我的私人微信,拉你进群