Knife4j文档请求异常(更新)

文章讲述了在SpringBoot的多模块项目中,如果Swagger2的注解@EnableSwagger2WebMvc不在启动类上可能导致的问题,以及如何通过在启动类上添加该注解来解决。另外,还讨论了SpringSecurity的白名单配置,强调了正确设置白名单以允许Swagger和特定登录接口的重要性,以及如何排查登录接口未放行的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 多模块注解不当引起

在SpringBoot项目中,如果是分不同的模块开发。
注解配置 @EnableSwagger2WebMvc不在启动类上,而是加到了其他模块的注解中,可能会导致这种情况发生。

我的是common一个单独的模块,在common模块中配置了WebMvcConfig。
然后在WebMvcConfig类上面加了注解@EnableSwagger2WebMvc.

那么,解决方法也很简单,在启动类上也添加上注解@EnableSwagger2WebMvc即可。

/**
 * @Author: KingWang
 * @Date: 2023/4/9
 * @Desc:
 **/
@Slf4j
@Configuration
//@EnableSwagger2WebMvc 分模块下,这个注解不在启动类模块中,是无效的
public class WebMvcConfig extends WebMvcConfigurationSupport {


    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        //swagger文档需要添加下面2行
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 扩展mvc框架的消息转换器
     * @param converters
     */
    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        log.info("扩展消息转换器...");
        //创建消息转换器对象
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        //设置对象转换器,底层使用Jackson将java对象转为Json
        messageConverter.setObjectMapper(new JacksonObjectMapper());
        //将上面的消息转换器对象追加到mvc框架的转换器容器中
        converters.add(0, messageConverter);
    }


    @Bean
    public Docket adminApiConfig(){
        List<Parameter> pars = new ArrayList<>();
        ParameterBuilder tokenPar = new ParameterBuilder();
        tokenPar.name("token")
                .description("用户token")
                .defaultValue("")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false)
                .build();
        pars.add(tokenPar.build());
        //添加head参数end

        Docket adminApi = new Docket(DocumentationType.SWAGGER_2)
                .groupName("adminApi")
                .apiInfo(adminApiInfo())
                .select()
                //只显示admin路径下的页面
                .apis(RequestHandlerSelectors.basePackage("com.guigutool.system.controller"))
                .paths(PathSelectors.regex("/admin/.*"))
                .build()
                .globalOperationParameters(pars);
        return adminApi;
    }

    private ApiInfo adminApiInfo(){

        return new ApiInfoBuilder()
                .title("后台管理系统-API文档")
                .description("本文档描述了后台管理系统微服务接口定义")
                .version("1.0")
                .contact(new Contact("guigutool", "http://guigutool.com", "guigutool@qq.com"))
                .build();
    }
}

启动类中加上该注解:

@EnableSwagger2WebMvc
@SpringBootApplication
@MapperScan("com.guigutool.system.mapper")
public class ServiceAuthApplication {

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

2. SpringSecurity白名单问题

白名单设置的不全或者不一致导致的。
在SpringSecurity中我们通常会增加配置类SecurityConfig如下设置:

@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

private static final String[] http_ignore_path = {"/v2/**","/swagger-resources","/webjars/**","/favicon.ico","/doc.html","/log/*","/admin/system/index/login/"};

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable()  //关闭csrf
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and().cors().configurationSource(corsConfigurationSource())
        .and()
        .authorizeRequests()
        .antMatchers(http_ignore_path).permitAll()
        .anyRequest().authenticated();

        //添加用户认证过滤器
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);


        //认证和权限
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler)
                .authenticationEntryPoint(authenticationEntryPoint);
    }

}

这里要特别注意http_ignore_path 这个数组设置的白名单。
Knife4j需要配置的白名单如下:

private static final String[] http_ignore_path = {"/v2/**","/swagger-resources","/webjars/**","/favicon.ico","/doc.html","/log/*","/admin/system/index/login/"};

除了最后两个"/log/*“,”/admin/system/index/login/"是日志和登录接口以外,其他的都需要放行。
之前设置登录接口的时候一直也是卡住,即使添加了白名单也不放行,后来仔细检查终于发现登录的请求地址写错了。
可以先在过滤器中打印出请求的URL信息如下:

        String requestURI = request.getRequestURI();
        log.info("请求URI:" + requestURI);

这样可以看到请求的地址信息,然后将这里显示的URI信息,然后将这里的信息填写到白名单中。
自己曾经在白名单中写登录请求地址时,多加了一个/ 导致一直登录失败。
在这里插入图片描述

### 解决 Knife4j 文档请求异常 500 错误 当遇到 Knife4j 文档请求返回 500 内部服务器错误时,可能的原因和对应的解决方案如下: #### 1. 版本兼容性问题 如果使用的 Spring Boot 或其他框架版本较高,可能会存在不兼容的情况。尝试降低 Spring Boot 的版本号可以解决问题[^2]。 #### 2. 启动类注解配置不当 对于某些项目结构,在启动类上添加 `@EnableSwagger2WebMvc` 注解有助于解决此问题。不过需要注意的是,在 Knife4j 3.x 及以上版本中已经支持自动配置,通常不需要再手动添加这个注解[^3]。 ```java // 对于低于3.x版本的Knife4j, 需要显式添加该注解 @SpringBootApplication @EnableSwagger2WebMvc // 如果是低版本则保留这行代码 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` #### 3. Gateway代理设置不合理 如果是基于微服务架构的应用程序,并且通过 API Gateway 访问 Swagger 资源,则应确保网关正确转发 `/v2/api-docs` 请求至目标服务实例。可以通过浏览器开发者工具中的网络面板来检查具体的 HTTP 响应状态码与消息体内容,从而定位具体原因并调整路由规则或路径映射关系[^4]。 #### 4. 缺少必要的初始化类 创建一个继承自 `SpringBootServletInitializer` 并重写其方法的类可以帮助完成一些额外的初始化工作,进而修复潜在的问题[^5]。 ```java public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(YourApplicationClass.class); } } ``` 上述措施能够有效应对大部分情况下发生的 Knife4j 文档请求异常 500 错误现象。然而实际开发过程中还可能存在更多复杂场景下的特殊情况,请根据具体情况灵活运用这些技巧进行排查处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

硅谷工具人

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

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

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

打赏作者

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

抵扣说明:

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

余额充值