Springboot整合swagger(knife4j3.0.3)(一)

作者:OHJ小白   

此文章是swagger的基础搭建,希望这篇文章可以帮到你学习swagger搭建


一、Swagger是什么?

        使用Swagger你只需要按照它的规范去定义接口及接口相关的信息,再通过Swagger衍生出来的一系列项目和工具,就可以做到生成各种格式的接口文档,以及在线接口调试页面等等,这不但可以方便前端人员查看接口与后端进行联调,还可以让后端人员自己进行接口的调试,大大增加开发的效率。

        swagger官网: API Documentation & Design Tools for Teams | Swagger

        knife4j是为Java MVC框架集成Swagger生成Api文档的增强解决方案,可以让接口文档页面变得更美观和功能变强大

        官网文档地址:Knife4j · 集Swagger2及OpenAPI3为一体的增强解决方案. | Knife4j

二、使用步骤

1.引入依赖

依赖如下(示例):

<!-- knife4j,Swagger的增强文档 -->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
	<artifactId>knife4j-spring-boot-starter</artifactId>
	<version>3.0.3</version>
</dependency>

2.代码

代码如下(示例):

package com.example.server.web.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.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
@EnableKnife4j
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .useDefaultResponseMessages(false)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.server.web.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .description("knife4j在线API接口文档")
                .contact(new Contact("YHJ","#", "2733247927@qq.com"))
                .version("v3.0.0")
                .title("knife4j在线API接口文档")
                .build();
    }
}

3.配置基本信息

Docket:摘要对象,通过对象配置描述文件的信息。

apiInfo:设置描述文件中信息。参数类型ApiInfo

select():返回ApiSelectorBuilder对象,通过对象调用build()可以创建Docket对象

ApiInfoBuilderApiInfo构建器。

apis:设置哪个包中内容被扫描

paths:可以设置满足什么样规则的url被生成接口文档。可以使用正则表达式进行匹配。  PathSelectors.any ()是代表匹配所有URL。

useDefaultResponseMessages实际开发中,大多数都是自定义状态码的;所以,就可以通过 useDefaultResponseMessages(false) 关闭默认状态码

4.常用注解

@Api加载Controller类上,表示对类的说明用法:@Api(tags = {"xxx"}),这样swagger上面才会显示你写的信息

@ApiModel添加在实体类上,实体类的描述信息

@ApiModelProperty添加实体类的属性上,属性的描述信息

@ApiOperation一般添加在方法上,描述方法的作用

@ApiImplicitParams表示一组参数说明

@ApiImplicitParam用在@ApiImplicitParams注解中,指定一个请求参数的各个方面的属性

@ApiParam:描述方法的参数的信息

5.访问文档首页

http://localhost:8080/doc.html

 

6、是否开启密码模式等配置

swagger还可以开启密码登录模式,只需要在application.yaml里面写上

knife4j:
  enable: true  #开启增强功能
  basic:
    enable: true    #开启密码模式
    username: admin   #用户名
    password: 123456  #密码

如图:


注意事项

  若访问文档首页的时候出现404,则需要检查自己的项目存不存在WebMvcConfigurationSupport类或者WebMvcConfigurer接口,若存在先在启动类上加@EnableWebMvc,还需要加上此配置:

@SpringBootApplication
public class SwaggerBootstrapUiDemoApplication  implements WebMvcConfigurer{
 
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

  官方的说明是:如果你是使用的老的版本SpringBoot,通过继承WebMvcConfigurationSupport来扩展SpringBoot相关的配置,则把以上配置加在相应的addResourceHandlers方法中即可官方的说明是:如果你是使用的老的版本SpringBoot,通过继承WebMvcConfigurationSupport来扩展SpringBoot相关的配置,则把以上配置加在相应的addResourceHandlers方法中即可

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你好!要将Spring Boot 3与Knife4j 4.0.0集成,你可以按照以下步骤进行操作: 1. 首先,在你的Spring Boot项目中添加Knife4j的依赖。在pom.xml文件中添加以下依赖项: ```xml <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>4.0.0</version> </dependency> ``` 2. 接下来,你需要创建一个配置类来配置Knife4j。在你的项目中创建一个名为`SwaggerConfig`(或者你自己喜欢的名字)的类,并添加`@Configuration`和`@EnableKnife4j`注解,如下所示: ```java @Configuration @EnableKnife4j public class SwaggerConfig { // 配置内容 } ``` 3. 在配置类中,你可以根据需要对Knife4j进行更多的自定义设置。以下是一些常用的配置选项: - 配置接口文档的标题、描述等信息: ```java @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) // 其他配置项 .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API文档") .description("这是一个示例API文档") .version("1.0.0") .build(); } ``` - 配置接口文档的访问路径: ```java @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .pathMapping("/") // 其他配置项 .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build(); } ``` - 配置接口文档的安全认证: ```java @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .securitySchemes(Lists.newArrayList(apiKey())) .securityContexts(Lists.newArrayList(securityContext())) // 其他配置项 .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build(); } private ApiKey apiKey() { return new ApiKey("token", "token", "header"); } private SecurityContext securityContext() { return SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.regex("^(?!auth).*$")) .build(); } private List<SecurityReference> defaultAuth() { AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; return Lists.newArrayList(new SecurityReference("token", authorizationScopes)); } ``` 4. 配置完成后,你可以启动你的Spring Boot应用程序,并访问`http://localhost:8080/doc.html`(根据你的配置进行相应调整)来查看生成的接口文档。 希望以上步骤对你有帮助!如果还有其他问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值