SpringBoot2接入Knife4j

接入过程

1.引入依赖

pom.xml

xml 复制代码
<!-- Knife4j -->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>3.0.3</version>
</dependency>

2.编写配置

src/main/java/com/example/netdisk/config/Knife4jConfig.java

java 复制代码
package com.example.netdisk.config;

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

@Configuration
public class Knife4jConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.netdisk.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("NetDisk API")
                .description("网盘系统接口文档")
                .version("1.0.0")
                .build();
    }
}

3.放行请求

src/main/java/com/example/netdisk/security/config/SecurityConfig.java

java 复制代码
.authorizeRequests()// 开始配置URL授权(新版可能用 authorizeHttpRequests)
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()// 预检请求放行
.antMatchers("/auth/**").permitAll()// 登录接口所有人都可访问
.antMatchers(
        "/swagger-ui.html",
        "/swagger-ui/**",
        "/webjars/**",
        "/v2/api-docs",
        "/v3/api-docs",
        "/swagger-resources/**",
        "/doc.html"
).permitAll()               //swagger路径放行
.anyRequest().authenticated()// 其他所有请求都需要认证

4.处理兼容

运行后报错:Failed to start bean 'documentationPluginsBootstrapper'

这属于 Springfox 和 Spring Boot 2.6 的兼容问题,需要额外配置:

src/main/resources/application.yml

yml 复制代码
spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

运行项目后访问:http://localhost:8080/doc.html

编写文档

相关推荐
子兮曰5 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰5 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
爱勇宝5 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
胡写代码5 天前
别再前后端各写一套表单校验了
java·后端
大勇前进5 天前
原生 PHP 还是 Laravel?小项目到底要不要上框架
后端
yuzhi_liu5 天前
我用 LangGraph4j 实现 Multi-Agent Supervisor
后端
alsmile5 天前
Node-RED 之外,国产规则引擎的新方案:基于标准语法,Go 先行实现
后端·开源·go
大白805 天前
PHP 内存溢出排查思路:看懂报错日志,精准定位问题
后端
二月龙5 天前
PHP 接口返回统一响应封装,让前后端对接更省心
后端
盖伦发发5 天前
软件工程SOLID 五大设计原则
后端·软件工程