Swagger3.0和Knife4j

本文档展示了如何在Spring Boot项目中整合Swagger3和Knife4j,创建详细的API接口文档。通过配置`pom.xml`引入相关依赖,设置` Knife4jConfiguration`和`SwaggerConfig`配置类,以及在`DemoController`和`UserController`中使用`@ApiOperation`注解,实现了接口的文档化。访问Swagger UI和Knife4j接口文档,可以查看和测试接口。

1、pom依赖


    <properties>
        <java.version>1.8</java.version>
        <spring.cloud.alibaba.version>2.2.6.RELEASE</spring.cloud.alibaba.version>
        <spring.boot.version>2.3.12.RELEASE</spring.boot.version>
        <spring.cloud.version>Hoxton.SR12</spring.cloud.version>
    </properties>
    
    <repositories>
        <repository>
            <id>alimaven</id>
            <name>aliyun maven</name>
            <url>https://maven.aliyun.com/nexus/content/repositories/central/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>alimaven</id>
            <name>aliyun maven</name>
            <url>https://maven.aliyun.com/nexus/content/repositories/central/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

 		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
             <version>2.3.12.RELEASE</version>
        </dependency>
        <!-- SpringBoot整合springfox-swagger3 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
        <!-- knife4j -->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>3.0.3</version>
        </dependency>
        <!-- swagger3 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

2、configuration

2.1、Knife4jConfiguration

package org.wuwangfu.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.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * @author: jcshen
 * @Date: 2022/11/15
 * @Description:Knife4j
 *
 *  接口文档界面:http://localhost:8080/doc.html#
 */

@Configuration
@EnableKnife4j
public class Knife4jConfiguration {

    //knife
    @Bean(value = "defaultApi2")
    public Docket defaultApi2() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .title("Knife4j渲染OpenAPI接口文档")
                        .description("# Knife4j渲染OpenAPI接口文档")
                        //.termsOfServiceUrl("http://www.xx.com/")
                        // .contact(new Contact("jcshen","027","wuwangfu.com"))
                        .version("1.0")
                        .build())
                //分组名称
                .groupName("3.X版本")
                .select()
                //这里指定Controller扫描包路径
                .apis(RequestHandlerSelectors.basePackage("org.wuwangfu.controller"))
                .paths(PathSelectors.any())
                .build();
    }
}

2.2、SwaggerConfig

package org.wuwangfu.config;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import io.swagger.annotations.ApiOperation;
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.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * @author: jcshen
 * @Date: 2022/11/15
 * @Description:配置Swagger 3.0,网页展示配置
 *
 *  接口文档界面:http://localhost:8080/swagger-ui/index.html
 */


@EnableOpenApi   // 开启Swagger自定义接口文档
@Configuration   // 相当于Spring配置中的<beans>
public class SwaggerConfig {
    @Bean   // 相当于Spring 配置中的<bean>
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }
    // API基础信息定义(就是更新Swagger默认页面上的信息)
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger3接口文档")
                .description("Swagger3接口文档")
               // .contact(new Contact("jcshen", "网址", "wuwangfu.com"))
                .version("v1.0")
                .build();
    }


}

3、启动类KnifeApplication

package org.wuwangfu;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author: jcshen
 * @Date: 2022/11/15
 * @Description:
 */

@Slf4j  //日志
@SpringBootApplication  //启动
@EnableSwagger2 //文档配置
public class KnifeApplication {

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

}

4、entity

package org.wuwangfu.entity;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * @author: jcshen
 * @Date: 2022/11/15
 * @Description:
 */

@Data
public class UserVO {

    @ApiModelProperty(value = "用户id")
    private String userId;
    @ApiModelProperty(value = "用户名")
    private String userName;
    @ApiModelProperty(value = "用户年龄")
    private Integer userAge;
    @ApiModelProperty(value = "用户密码")
    private String password;
    @ApiModelProperty(value = "手机号")
    private String phone;
    @ApiModelProperty(value = "用户地址")
    private String address;


}

5、controller

5.1、DemoController

package org.wuwangfu.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.wuwangfu.entity.UserVO;

/**
 * @author: jcshen
 * @Date: 2022/11/15
 * @Description:
 *  接口文档界面:http://localhost:8080/swagger-ui/index.html
 *
 */

@RestController
@RequestMapping("/demo")
@Api(tags = "demo模块")
public class DemoController {

    @GetMapping("/userList")
    @ApiOperation(value = "查询所有的用户信息")
    public UserVO getUserList() {
        UserVO vo = new UserVO();
        vo.setUserId("nihao");
        vo.setUserName("你好");
        vo.setUserAge(18);
        vo.setPassword("123456");
        vo.setPhone("12345612345");
        vo.setAddress("你好你好你好你好你好你好你好");
        return vo;
    }
}

5.2、UserController

package org.wuwangfu.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.wuwangfu.entity.UserVO;

/**
 * @author: jcshen
 * @Date: 2022/11/15
 * @Description:
 *  接口文档界面:http://localhost:8080/doc.html#
 *
 */

@RestController
@RequestMapping("/user")
@Api(tags = "用户模块")
public class UserController {

    @GetMapping("/userList")
    @ApiOperation(value = "查询所有的用户信息")
    public UserVO getUserList() {
        UserVO vo = new UserVO();
        vo.setUserId("nihao");
        vo.setUserName("你好");
        vo.setUserAge(18);
        vo.setPassword("123456");
        vo.setPhone("12345612345");
        vo.setAddress("你好你好你好你好你好你好你好");
        return vo;
    }
}

6、接口访问

swagger接口文档界面:http://localhost:8080/swagger-ui/index.html
knife接口文档界面:http://localhost:8080/doc.html#

在 RuoYi 3.8.6 中集成使用 Swagger 3.0Knife4j 主要涉及以下几个步骤: ### 添加依赖 在 `pom.xml` 文件中添加 Swagger 3.0 Knife4j 的相关依赖。确保使用的是与 SpringDoc OpenAPI 兼容的版本。 ```xml <!-- SpringDoc OpenAPI (Swagger 3.0) --> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.6.14</version> </dependency> <!-- Knife4j 增强UI支持 --> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-openapi3-ui-spring-boot-starter</artifactId> <version>3.0.3</version> </dependency> ``` ### 配置 Swagger 3.0 在 `application.yml` 或 `application.properties` 中配置 Swagger 3.0 的基本信息。 ```yaml springdoc: swagger-ui: url: /v3/api-docs/swagger-config api-docs: path: /v3/api-docs ``` ### 创建 Swagger 配置类 创建一个配置类来启用 Swagger 并配置相关参数。 ```java import io.swagger.v3.oas.annotations.OpenAPIDefinition; import io.swagger.v3.oas.annotations.info.Info; import org.springframework.context.annotation.Configuration; @Configuration @OpenAPIDefinition(info = @Info(title = "RuoYi API", version = "3.0", description = "RuoYi 3.8.6 API 文档")) public class SwaggerConfig { } ``` ### 配置 Knife4j UI Knife4j 提供了增强的 UI 界面,可以通过自定义配置进一步优化文档展示效果。 ```java import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; import org.springframework.context.annotation.Configuration; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableKnife4j @EnableSwagger2 public class Knife4jConfig { } ``` ### 使用 Swagger 注解 在控制器中使用 Swagger 3.0 的注解来描述 API 接口信息。 ```java import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api") @Tag(name = "用户管理", description = "用户管理相关的API接口") public class UserController { @GetMapping("/users/{id}") @Operation(summary = "获取用户信息", description = "根据ID获取用户详细信息") @ApiResponse(responseCode = "200", description = "成功获取用户信息") public User getUserById( @Parameter(description = "用户ID", required = true) @PathVariable Long id) { // 业务逻辑 return new User(); } } ``` ### 访问 Knife4j UI 启动项目后,访问以下地址查看 Knife4j 提供的 UI 界面: ``` http://localhost:8080/doc.html ``` ### 验证集成效果 确保可以通过 Knife4j UI 查看测试 API 接口,并确认文档信息是否正确显示。 --- ### 注意事项 - 确保依赖版本与 RuoYi 3.8.6 兼容。 - 如果项目中存在其他 Swagger 配置,请检查是否有冲突。 - Knife4j 的 UI 界面提供了更多增强功能,如接口调试、离线文档导出等[^1]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值