SpringBoot 整合 Knife4j


前言

后端开发,提供 Restful 接口给前端,Swagger3 提供 Restful 的接口文档自动生成和在线接口调试。Knife4j 是对 Swagger 进一步封装,优化了 API 文档的 UI 界面。

一、Pom 导入 Knife4j 依赖

<dependency>
     <groupId>com.github.xiaoymin</groupId>
     <artifactId>knife4j-spring-boot-starter</artifactId>
     <version>3.0.3</version>
</dependency>

二、修改 application.yaml 配置文件

# knife4j配置
knife4j:
  # 启用
  enable: true
  # 增强配置
  setting:
    enableSwaggerModels: true
    enableDocumentManage: true
    enableHost: false
    enableHostText: http://localhost
    enableRequestCache: true
    enableFilterMultipartApis: false
    enableFilterMultipartApiMethodType: POST
    language: zh-CN
  # 开启屏蔽文档资源
  production: true

三、创建一个 Knife4jConfig 类

@Configuration
@EnableKnife4j
public class Knife4jConfig {

    @Bean
    public Docket docket1() {
        return new Docket(DocumentationType.SWAGGER_2).groupName("A");
    }

    @Bean
    public Docket docket2() {
        return new Docket(DocumentationType.SWAGGER_2).groupName("B");
    }

    @Bean
    public Docket docket3() {
        return new Docket(DocumentationType.SWAGGER_2).groupName("C");
    }


    @Bean
    public Docket docket(Environment environment) {
        // 设置要显示swagger环境
        Profiles profiles = Profiles.of("dev", "test");
        // 判断是否处在在自己设定的环境当中
        boolean flag = environment.acceptsProfiles(profiles);

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                // 是否启动swagger
                .enable(flag)
                // 分组名称
                .groupName("雪山")
                // 设置哪些接口暴露给Swagger展示
                .select()

                /**
                 * 配置要扫描的接口的方式 RequestHandlerSelectors
                 * basePackage:指定要扫描的包
                 * any(): 扫描全部
                 * none():不扫描
                 * withClassAnnotation(RestController.class): 扫描类上有RestController.class的注解
                 * withMethodAnnotation(GetMapping.class):    扫描方法上的注解
                 */

                // 扫描所有有注解的api,用这种方式更灵活
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 指定Controller扫描包路径
                // .apis(RequestHandlerSelectors.basePackage("com.xb.controller"))
                // 过滤请求路径
                .paths(PathSelectors.ant("/xb/**"))
                .build();
    }

    private ApiInfo apiInfo() {
        // 作者信息
        Contact contact = new Contact("哈哈哈", "https://blog.csdn.net/xx", "xx@qq.com");

        return new ApiInfo(
                "SwaggerAPI文档",
                "远航",
                "v1.0",
                "https://github.com/xx",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<>()
        );
    }
}

四、Api 注解的使用

1、控制类

@Api(value = "用户controller", tags = {"用户操作接口"})
@RestController
public class UserController {
    @ApiOperation(value = "获取用户信息")
    @GetMapping("/xb/getUserInfo")
    public User getUserInfo(@ApiParam(name = "id", value = "用户id", required = true) Long id, @ApiParam(name = "username", value = "用户名") String username) {
        return new User();
    }

    @ApiOperation("更改用户信息")
    @PostMapping("/xb/updateUserInfo")
    public int updateUserInfo(@RequestBody @ApiParam(name = "用户对象", value = "传入json格式", required = true) User user) {
        return 999;
    }
}

2、实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "", description = "用户对象user")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "用户名", example = "xx")
    private String username;

    @ApiModelProperty(value = "状态", required = true)
    private Integer state;

    private String password;

    private String nickName;

    private Integer isDeleted;

    @ApiModelProperty(value = "id数组", hidden = true)
    private String[] ids;

    private List<String> idList;
}

五、启动测试访问

启动项目,在浏览器输入 http://localhost:8080/doc.html 就可以看到接口的信息。
在这里插入图片描述

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: Knife4j是一个基于Swagger-Bootstrap-UI的开源项目,可以在Spring Boot整合使用。 整合步骤如下: 1. 引入knife4j的依赖 2. 配置knife4j的相关参数 3. 在启动类上添加@EnableSwaggerBootstrapUi注解 4. 在需要使用knife4j的接口上添加@ApiOperation注解 5. 启动项目,访问http://{host}:{port}/swagger-ui.html即可查看接口文档 ### 回答2: Spring Boot是一种快速、便捷的应用开发框架,Knife4j是一种专业的Java接口文档生成工具,将它们两者结合起来可以提供一个更为便捷、高效的开发体验。下面是关于如何整合Spring BootKnife4j的详细过程: 1.引入依赖 在pom.xml中引入如下依赖: ``` <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>3.0.2</version> </dependency> ``` 2. 应用配置 在application.yml文件中进行应用配置: ``` knife4j: title: Demo API Docs description: Demo API Description version: "1.0" license: name: MIT url: https://github.com/mit-license contact: name: Demo url: https://github.com/demo email: [email protected] show: true enable: true scan-package: com.demo.controller ``` 其中,title、description、version等属性可根据实际情况进行修改,scan-package则是指定需要扫描的API包名。 3. 编写API文档 在Controller类的方法上添加@Api注解,如下所示: ``` @RestController @RequestMapping(value = "/user") @Api(value = "用户相关接口", tags = {"用户相关接口"}) public class UserController { @ApiOperation(value = "获取所有用户信息", notes = "获取所有用户信息") @GetMapping(value = "/list") public ResponseEntity<List<User>> list() { // ... } } ``` 其中,@Api注解指定API的名称和描述信息,@ApiOperation注解则指定每个API方法的名称和描述信息。 4. 启动应用 启动应用,浏览器访问http://localhost:8080/doc.html,即可查看生成的API文档。 总结 整合Spring BootKnife4j可以方便快捷地生成API文档,提高开发效率和开发者体验。通过上述步骤,可以快速上手并使用该工具。 ### 回答3: Spring Boot 是一种针对 Spring 框架的快速应用开发框架。而 Knife4j 是基于 Swagger 的文档生成工具,用来生成高质量的 API 文档,且支持在线调试和 Mock 数据。 对于 Spring Boot 的开发者来说,整合 Knife4j 可以帮助他们更加方便地生成 API 文档和在线调试,提高开发速度和效率。以下就是整合步骤: 1. 添加依赖和插件 在 pom.xml 文件中添加以下依赖和插件: ``` <!-- Swagger-UI --> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.9.6</version> </dependency> <!-- Swagger-Annotations --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <!-- Knife4j --> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>3.0.2</version> </dependency> <!-- 插件 --> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <!-- Swagger2Markup --> <plugin> <groupId>io.github.swagger2markup</groupId> <artifactId>swagger2markup-maven-plugin</artifactId> <version>${swagger2markup.version}</version> <configuration> <swaggerInput>${project.build.directory}/swagger/swagger.json</swaggerInput> <outputDirAsPath>true</outputDirAsPath> <outputDir>${project.build.directory}/docs</outputDir> <config> <swagger2markup.extensions.interceptors.paths> <interceptor path="*.json"></interceptor> </swagger2markup.extensions.interceptors.paths> </config> </configuration> </plugin> </plugins> </build> ``` 其中,Swagger-UI 是 Swagger 的界面展示工具,Knife4j 依赖于 Swagger-UI,因此需要同时引入 Swagger-UI 和 Swagger-Annotations。而 Swagger-Annotations 是用来标识接口的注解,通过这些注解生成接口文档。 2. 配置 Swagger 在 application.yml 或 application.properties 中添加以下配置: ``` ## Swagger swagger: enabled: true title: Knife4j整合Swagger2接口文档 description: Knife4j整合Swagger2,可以快速生成API文档 version: 2.0 contact: name: FZF url: http://fzf.blog.csdn.net/ basePackage: com.fzf.knife4j host: localhost:8080 protocols: http,https ``` Property | Default | Comment ----------------|-----------------------|--------- `enabled` | true | 是否开启 Swagger `title` | Application Name | Swagger 页面标题 `description` | EMPTY | Swagger 页面描述 `version` | 1.0 | API 版本号 `contact.name` | EMPTY | 联系人姓名 `contact.url` | EMPTY | 联系人 URL `basePackage` | Application Package | 扫描的包路径 `host` | EMPTY | 访问地址 `protocols` | http | 协议,concatenated list of protocols (http, https, ws, wss) 3. 配置 Knife4j 在 application.yml 或 application.properties 中添加以下配置: ``` ## Knife4j knife4j: enabled: true title: Knife4j整合Swagger2接口文档 description: Knife4j整合Swagger2,可以快速生成API文档 version: 2.0 contact: name: FZF url: http://fzf.blog.csdn.net/ license: name: Apache-2.0 url: http://www.apache.org/licenses/LICENSE-2.0 termsOfServiceUrl: https://github.com/fuzhengwei/swagger-bootstrap-ui/blob/master/LICENSE basePackage: com.fzf.knife4j versionGroup: v2 scanPackages: com.fzf.knife4j host: localhost:8080 protocols: http,https globalOperationParameters: - name: authToken description: token modelRef: string parameterType: header required: false ``` Property | Default | Comment --------------------------------|-------------------------|--------- `enabled` | true | 是否开启 Knife4j `title` | Application Name | Knife4j 页面标题 `description` | EMPTY | Knife4j 页面描述 `version` | 1.0 | API 版本号 `contact.name` | EMPTY | 联系人姓名 `contact.url` | EMPTY | 联系人 URL `license.name` | EMPTY | 许可证名称 `license.url` | EMPTY | 许可证 URL `termsOfServiceUrl` | EMPTY | 服务条款 URL `basePackage` | Application Package | 扫描的包路径 `versionGroup` | v1, v2, ... | API 版本组名 `scanPackages` | EMPTY | 扫描的包路径 `host` | EMPTY | 访问地址 `protocols` | http | 协议,concatenated list of protocols (http, https, ws, wss) `globalOperationParameters` | EMPTY | 全局参数,例如鉴权 token 等 4. 创建 Swagger 配置类 在 Spring Boot 项目中创建一个 Swagger 配置类: ``` @Configuration @EnableSwagger2 @Import(BeanValidatorPluginsConfiguration.class) public class SwaggerConfiguration { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select() .apis(RequestHandlerSelectors.basePackage("com.fzf.knife4j")).paths(PathSelectors.any()).build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder().title("Knife4j整合Swagger2接口文档").description("Knife4j整合Swagger2,可以快速生成API文档") .termsOfServiceUrl("https://github.com/fuzhengwei/swagger-bootstrap-ui").version("2.0").build(); } } ``` 其中,`@Configuration` 注解用于标识该类为 Spring 配置类;`@EnableSwagger2` 注解用于开启 Swagger2;`@Import(BeanValidatorPluginsConfiguration.class)` 注解用于启用 Hibernate Validator 注解,这是为了在 Swagger UI 中验证接口参数的有效性。`api()` 方法用于生成 Swagger Docket(API 文档),`apiInfo()` 方法用于指定 API 文档的基本信息,例如标题、描述、版本等。 5. 启动项目 在项目启动后,访问 http://localhost:8080/swagger-ui.html 可以看到 Swagger 的页面,访问 http://localhost:8080/doc.html 可以看到 Knife4j 的页面,访问 http://localhost:8080/docs/index.html 可以看到导出的文档。 总结: 通过以上步骤即可成功地将 Knife4j 整合Spring Boot 项目中,实现 API 文档的自动生成,以及在线调试和 Mock 数据功能。整合后的 API 文档可以更加规范、高效地管理和维护 API 文档,提高接口文档的可读性和可维护性,同时也提高了接口的开发效率和质量。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

-.- !

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值