SpringBoot整合Knife4j

版本

我用的是SpringBoot 2.7.3+Knife4j3.0.3

添加依赖

当然最新Knife4j

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

除此之外还需要SpringMvc的依赖

添加配置类

Knife4jConfig:

package com.example.springjpaquery.config;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Knife4j配置类
 */
@Configuration
@EnableOpenApi
// @EnableKnife4j
// @EnableSwagger2
public class Knife4jConfig {
    @Bean
    public Docket docket() {
        Docket docket = new Docket(DocumentationType.OAS_30)
                .apiInfo(new ApiInfoBuilder()
                        .title("Aip在线文档")
                        .description("我的描述")
                        // .termsOfServiceUrl("http://www.xx.com/")
                        .contact(new Contact("knife", "https://blog.csdn.net/abst122", "xx@qq.com"))
                        .version("1.0")
                        .build())
                // 分组名称
                .groupName("all")
                .select()
                // 这里指定Controller扫描包路径
                .apis(RequestHandlerSelectors.basePackage("com.example.springjpaquery"))
                .paths(PathSelectors.any())
                .build();

        return docket;
    }
}

添加controller

IndexController:

package com.example.springjpaquery.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 首页模块
 */
@Api(tags = {"首页模块"})
@RestController
public class IndexController {
    
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "name", value = "姓名")
    })
    @ApiOperation(value = "", notes = "", httpMethod = "GET")
    @GetMapping("/sayHi")
    public ResponseEntity<String> sayHi(@RequestParam(value = "name")String name){
        return ResponseEntity.ok("Hi:"+name);
    }
}

启动测试

如果报错
在这里插入图片描述
空指针异常,百度一下,有两个解决方案,忘记从哪里看的了,感谢!

  1. 降低springboot的版本一般降到2.5.7即可,其他版本没试过
  2. 在主程序启动类中加上 @EnableWebMvc
    既然使用MVC就要对静态资源进行放行
    其实可以不用加@EnableWebMvc,springboot已经帮我们做了
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
    //设置静态资源访问过滤,当前类需要设置为配置类,并被扫描加载
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    //当访问/pages/????时候,从/pages目录下查找内容
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }
}

访问

http://localhost:8889/doc.html
在这里插入图片描述

yml配置

knife4j:
  # 是否开启加强模式 true开启  false关闭
  enable: true
  setting:
    # 是否开启调试功能  true开启  false关闭
    enableDebug: true
  basic:
    # 是否开启认证功能  true开启  false关闭
    enable: true
    username: test
    password: 123456
knife4j:
  # 开启增强配置
  enable: true
  # 开启生产环境屏蔽
  production: true
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 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: demo@qq.com 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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值