【SpringBoot应用篇】SpringBoot集成Knife4j在线接口文档

【SpringBoot应用篇】SpringBoot集成Knife4j在线接口文档

  • knife4j介绍
  • knife4j入门使用
    • pom
    • User实体类
    • UserController类
    • PersonController类
    • 配置属性类Knife4jProperties
    • application.yml
    • 配置类Knife4jAutoConfiguration
    • 启动类Knife4jDemoApplication

knife4j介绍

knife4j是为Java MVC框架集成Swagger生成Api文档的增强解决方案,前身是swagger-bootstrap-ui,取名knife4j是希望它能像一把匕首一样小巧,轻量,并且功能强悍!其底层是对Springfox的封装,使用方式也和Springfox一致,只是对接口文档UI进行了优化。

核心功能

  • 文档说明:根据Swagger的规范说明,详细列出接口文档的说明,包括接口地址、类型、请求示例、请求参数、响应示例、响应参数、响应码等信息,对该接口的使用情况一目了然。

  • 在线调试:提供在线接口联调的强大功能,自动解析当前接口参数,同时包含表单验证,调用参数可返回接口响应内容、headers、响应时间、响应状态码等信息,帮助开发者在线调试。

knife4j入门使用

pom

<parent>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-parentartifactId>
    <version>2.2.2.RELEASEversion>
parent>
<modelVersion>4.0.0modelVersion>

<artifactId>springboot-knife4jartifactId>

<properties>
    <maven.compiler.source>8maven.compiler.source>
    <maven.compiler.target>8maven.compiler.target>
properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
    dependency>
    <dependency>
        <groupId>com.github.xiaoymingroupId>
        <artifactId>knife4j-spring-boot-starterartifactId>
        <version>2.0.1version>
    dependency>
    <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
    dependency>
dependencies>

User实体类

@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;
}

UserController类

@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {
    @GetMapping("/getUsers")
    @ApiOperation(value = "查询所有用户", notes = "查询所有用户信息")
    public List<User> getAllUsers(){
        User user = new User();
        user.setId(100);
        user.setName("风雨修");
        user.setAge(20);
        user.setAddress("bj");
        List<User> 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";
    }
}

PersonController类

@RestController
@RequestMapping("/person")
@Api(tags = "人员管理")
public class PersonController {
    @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";
    }
}

配置属性类Knife4jProperties

@Data
@ConfigurationProperties(prefix = "knife4j")
public class Knife4jProperties {
    private String title = "在线文档"; //标题
    private String group = ""; //自定义组名
    private String description = "在线文档"; //描述
    private String version = "1.0"; //版本
    private Contact contact = new Contact(); //联系人
    private String basePackage = "cn.zysheep.controller"; //swagger会解析的包路径
    private List<String> basePath = new ArrayList<>(); //swagger会解析的url规则
    private List<String> excludePath = new ArrayList<>();//在basePath基础上需要排除的url规则
    private Map<String, DocketInfo> 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<String> basePath = new ArrayList<>(); //swagger会解析的url规则
        private List<String> 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 = "zysheep"; //联系人
        private String url = ""; //联系人url
        private String email = ""; //联系人email
    }
}

application.yml

server:
  port: 7788
knife4j:
  enabled: true #是否启用knife4j
  base-package: cn.zysheep.controller

配置类Knife4jAutoConfiguration

@Configuration
@ConditionalOnProperty(name = "knife4j.enabled", havingValue = "true", matchIfMissing = true)
@EnableSwagger2
@EnableConfigurationProperties(Knife4jProperties.class)
public class Knife4jAutoConfiguration implements BeanFactoryAware {
    @Autowired
    Knife4jProperties knife4jProperties;

    private BeanFactory beanFactory;

    @Bean
    @ConditionalOnMissingBean
    public List<Docket> createRestApi(){
        ConfigurableBeanFactory configurableBeanFactory = (ConfigurableBeanFactory) beanFactory;
        List<Docket> docketList = new LinkedList<>();
        // 没有分组
        if (knife4jProperties.getDocket().isEmpty()) {
            Docket docket = createDocket(knife4jProperties);
            configurableBeanFactory.registerSingleton(knife4jProperties.getTitle(), docket);
            docketList.add(docket);
            return docketList;
        }
        // 分组创建
        for (String groupName : knife4jProperties.getDocket().keySet()){
            Knife4jProperties.DocketInfo docketInfo =
                    knife4jProperties.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<Predicate<String>> basePath = new ArrayList<>();
            for (String path : docketInfo.getBasePath()) {
                basePath.add(PathSelectors.ant(path));
            }

            // exclude-path处理
            List<Predicate<String>> 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(Knife4jProperties knife4jProperties) {
        return new ApiInfoBuilder()
                //页面标题
                .title(knife4jProperties.getTitle())
                //创建人
                .contact(new Contact(knife4jProperties.getContact().getName(),
                        knife4jProperties.getContact().getUrl(),
                        knife4jProperties.getContact().getEmail()))
                //版本号
                .version(knife4jProperties.getVersion())
                //描述
                .description(knife4jProperties.getDescription())
                .build();
    }

    //创建接口文档对象
    private Docket createDocket(Knife4jProperties knife4jProperties) {
        //API 基础信息
        ApiInfo apiInfo = apiInfo(knife4jProperties);

        // base-path处理
        // 当没有配置任何path的时候,解析/**
        if (knife4jProperties.getBasePath().isEmpty()) {
            knife4jProperties.getBasePath().add("/**");
        }
        List<Predicate<String>> basePath = new ArrayList<>();
        for (String path : knife4jProperties.getBasePath()) {
            basePath.add(PathSelectors.ant(path));
        }

        // exclude-path处理
        List<Predicate<String>> excludePath = new ArrayList<>();
        for (String path : knife4jProperties.getExcludePath()) {
            excludePath.add(PathSelectors.ant(path));
        }

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo)
                .groupName(knife4jProperties.getGroup())
                .select()
                .apis(RequestHandlerSelectors.basePackage(knife4jProperties.getBasePackage()))
                .paths(Predicates.and(Predicates.not(Predicates.or(excludePath)),Predicates.or(basePath)))
                .build();
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}

启动类Knife4jDemoApplication

@SpringBootApplication
public class Knife4jDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(Knife4jDemoApplication.class, args);
    }
}

执行启动类main方法启动项目,访问地址:http://localhost:7788/doc.html
【SpringBoot应用篇】SpringBoot集成Knife4j在线接口文档_第1张图片

你可能感兴趣的:(#,SpringBoot,spring,boot,java,后端)