无论是前端还是后端,都多少被接口文档折磨过。前端抱怨后端给的接口文档与实际情况不一致。后端又觉得编写及维护接口文档会耗费不少精力,经常来不及更新。
使用Swagger只需要按照规范去定义接口及接口信息。再通过Swagger衍生出来的一系列项目和工具,就可以做到生成各种格式的接口文档,生成多种语言的客户端和服务端的代码,以及在线接口调试页面等等。按照新的开发模式,在开发新版本或者迭代版本的时候,只需要更新Swagger描述文件,就可以自动生成接口文档和客户端服务端代码,做到调用端代码、服务端代码以及接口文档的一致性。
为了简化swagger使用,Spring对swagger进行了整合,并命名Springfox
io.springfox
springfox-swagger-ui
2.9.2
io.springfox
springfox-swagger2
2.9.2
1、导入上面的依赖
2、创建application.yml文件
server:
port: 9000
3、创建实体类User和Menu
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel(description = "用户实体")
public class User {
@ApiModelProperty(value = "主键")
private int id;
@ApiModelProperty(value = "姓名")
private String name;
@ApiModelProperty(value = "年龄")
private int age;
@ApiModelProperty(value = "地址")
private String address;
}
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel(description = "菜单实体")
public class Menu {
@ApiModelProperty(value = "主键")
private int id;
@ApiModelProperty(value = "菜单名称")
private String name;
}
4、创建UserController和MenuController
import cn.itcast.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/user")
@Api(tags = "用户控制器")
public class UserController {
@GetMapping("/getUsers")
@ApiOperation(value = "查询所有用户", notes = "查询所有用户信息")
public List getAllUsers(){
User user = new User();
user.setId(100);
user.setName("itcast");
user.setAge(20);
user.setAddress("bj");
List list = new ArrayList<>();
list.add(user);
return list;
}
@PostMapping("/save")
@ApiOperation(value = "新增用户", notes = "新增用户信息")
public String save(@RequestBody User user){
return "OK";
}
@PutMapping("/update")
@ApiOperation(value = "修改用户", notes = "修改用户信息")
public String update(@RequestBody User user){
return "OK";
}
@DeleteMapping("/delete")
@ApiOperation(value = "删除用户", notes = "删除用户信息")
public String delete(int id){
return "OK";
}
@ApiImplicitParams({
@ApiImplicitParam(name = "pageNum", value = "页码",
required = true, type = "Integer"),
@ApiImplicitParam(name = "pageSize", value = "每页条数",
required = true, type = "Integer"),
})
@ApiOperation(value = "分页查询用户信息")
@GetMapping(value = "page/{pageNum}/{pageSize}")
public String findByPage(@PathVariable Integer pageNum,
@PathVariable Integer pageSize) {
return "OK";
}
}
import cn.itcast.entity.Menu;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/menu")
@Api(tags = "菜单控制器")
public class MenuController {
@GetMapping("/getMenus")
@ApiOperation(value = "查询所有菜单", notes = "查询所有菜单信息")
public List
5、创建配置类SwaggerAutoConfiguration (重点)
都是固定的以后直接复制下面这个就可以了 改一下扫描的包位置就好
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
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.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerAutoConfiguration {
@Bean
public Docket createRestApi1() {
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()).groupName("用户接口组")
.select()
//为当前包路径
.apis(RequestHandlerSelectors.basePackage("cn.itcast.controller.user"))
.build();
return docket;
}
@Bean
public Docket createRestApi2() {
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()).groupName("菜单接口组")
.select()
//为当前包路径
.apis(RequestHandlerSelectors.basePackage("cn.itcast.controller.menu"))
.build();
return docket;
}
//构建 api文档的详细信息
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title("API接口文档")
//创建人
.contact(new Contact("黑马程序员", "http://www.itheima.com", ""))
//版本号
.version("1.0")
//描述
.description("API 描述")
.build();
}
}
6、创建启动类SwaggerDemoApplication
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SwaggerDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SwaggerDemoApplication.class, args);
}
}
7、执行启动类main方法启动项目,访问地址:http://localhost:9000/swagger-ui.html
knife4j是对Swagger文档的增强解决方案,底层是对Springfox的(boot整合swagger)的封装,是对接口文档UI进行优化,注解都是swagger一样的
核心功能
1、创建maven工程knife4j_demo并配置pom.xml文件,导入knife4j依赖
com.github.xiaoymin
knife4j-spring-boot-starter
2.0.1
2、创建实体类User和Menu(上面案例已经写过)
3、创建UserController和MenuController(上面案例已经写过)
4、创建配置属性类SwaggerProperties,以后就不用频繁改controller类
import lombok.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/*
*配置属性类,用于封装接口文档相关属性,从配置文件读取信息封装成当前对象
*/
@Data
@ConfigurationProperties(prefix = "pinda.swagger")
public class SwaggerProperties {
private String title = "在线文档"; //标题
private String group = ""; //自定义组名
private String description = "在线文档"; //描述
private String version = "1.0"; //版本
private Contact contact = new Contact(); //联系人
private String basePackage = "com.itheima.pinda"; //swagger会解析的包路径
private List basePath = new ArrayList<>(); //swagger会解析的url规则
private List excludePath = new ArrayList<>();//在basePath基础上需要排除的url规则
private Map docket = new LinkedHashMap<>(); //分组文档
public String getGroup() {
if (group == null || "".equals(group)) {
return title;
}
return group;
}
@Data
public static class DocketInfo {
private String title = "在线文档"; //标题
private String group = ""; //自定义组名
private String description = "在线文档"; //描述
private String version = "1.0"; //版本
private Contact contact = new Contact(); //联系人
private String basePackage = ""; //swagger会解析的包路径
private List basePath = new ArrayList<>(); //swagger会解析的url规则
private List excludePath = new ArrayList<>();//在basePath基础上需要排除的url
public String getGroup() {
if (group == null || "".equals(group)) {
return title;
}
return group;
}
}
@Data
public static class Contact {
private String name = "pinda"; //联系人
private String url = ""; //联系人url
private String email = ""; //联系人email
}
}
5、创建application.yml文件
server:
port: 7788
pinda:
swagger:
enabled: true #是否启用swagger
docket:
user:
title: 用户模块
base-package: cn.itcast.controller.user
menu:
title: 菜单模块
base-package: cn.itcast.controller.menu
6、创建配置类SwaggerAutoConfigurat ion
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
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.EnableSwagger2;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
@Configuration
@ConditionalOnProperty(name = "pinda.swagger.enabled", havingValue = "true",
matchIfMissing = true)
@EnableSwagger2
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerAutoConfiguration implements BeanFactoryAware {
@Autowired
SwaggerProperties swaggerProperties;
private BeanFactory beanFactory;
@Bean
@ConditionalOnMissingBean
public List createRestApi(){
ConfigurableBeanFactory configurableBeanFactory =
(ConfigurableBeanFactory) beanFactory;
List docketList = new LinkedList<>();
// 没有分组
if (swaggerProperties.getDocket().isEmpty()) {
Docket docket = createDocket(swaggerProperties);
configurableBeanFactory.registerSingleton(swaggerProperties.getTitle(),
docket);
docketList.add(docket);
return docketList;
}
// 分组创建
for (String groupName : swaggerProperties.getDocket().keySet()){
SwaggerProperties.DocketInfo docketInfo =
swaggerProperties.getDocket().get(groupName);
ApiInfo apiInfo = new ApiInfoBuilder()
//页面标题
.title(docketInfo.getTitle())
//创建人
.contact(new Contact(docketInfo.getContact().getName(),
docketInfo.getContact().getUrl(),
docketInfo.getContact().getEmail()))
//版本号
.version(docketInfo.getVersion())
//描述
.description(docketInfo.getDescription())
.build();
// base-path处理
// 当没有配置任何path的时候,解析/**
if (docketInfo.getBasePath().isEmpty()) {
docketInfo.getBasePath().add("/**");
}
List> basePath = new ArrayList<>();
for (String path : docketInfo.getBasePath()) {
basePath.add(PathSelectors.ant(path));
}
// exclude-path处理
List> excludePath = new ArrayList<>();
for (String path : docketInfo.getExcludePath()) {
excludePath.add(PathSelectors.ant(path));
}
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo)
.groupName(docketInfo.getGroup())
.select()
//为当前包路径
.apis(RequestHandlerSelectors.basePackage(docketInfo.getBasePackage()))
.paths(Predicates.and(Predicates.not(Predicates.or(excludePath)),Predicates.or(basePath)))
.build();
configurableBeanFactory.registerSingleton(groupName, docket);
docketList.add(docket);
}
return docketList;
}
//构建 api文档的详细信息
private ApiInfo apiInfo(SwaggerProperties swaggerProperties) {
return new ApiInfoBuilder()
//页面标题
.title(swaggerProperties.getTitle())
//创建人
.contact(new Contact(swaggerProperties.getContact().getName(),
swaggerProperties.getContact().getUrl(),
swaggerProperties.getContact().getEmail()))
//版本号
.version(swaggerProperties.getVersion())
//描述
.description(swaggerProperties.getDescription())
.build();
}
//创建接口文档对象
private Docket createDocket(SwaggerProperties swaggerProperties) {
//API 基础信息
ApiInfo apiInfo = apiInfo(swaggerProperties);
// base-path处理
// 当没有配置任何path的时候,解析/**
if (swaggerProperties.getBasePath().isEmpty()) {
swaggerProperties.getBasePath().add("/**");
}
List> basePath = new ArrayList<>();
for (String path : swaggerProperties.getBasePath()) {
basePath.add(PathSelectors.ant(path));
}
// exclude-path处理
List> excludePath = new ArrayList<>();
for (String path : swaggerProperties.getExcludePath()) {
excludePath.add(PathSelectors.ant(path));
}
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo)
.groupName(swaggerProperties.getGroup())
.select()
.apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
.paths(Predicates.and(Predicates.not(Predicates.or(excludePath)),Predicates.or(basePath)))
.build();
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
}
7、创建启动类SwaggerDemoApplication
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SwaggerDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SwaggerDemoApplication.class, args);
}
}
8、执行启动类main方法启动项目,访问地址:http://localhost:7788/doc.html
server:
port: 7788
pinda:
swagger:
enabled: true #是否启用swagger
title: test模块
base-package: cn.itcast.controller