解决Swagger3接口文档无法访问

时间:2025-03-20 07:22:27

项目整合 Swagger3 生成的接口文档无法正常访问

解决方法是在 WebMvcConfig 配置类中重写 WebMvcConfigurationSupport 中的 addResourceHandlers 方法,设置静态资源映射。

WebMvcConfig

import ;
import ;
import ;

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    /**
     * @Description: 设置静态资源映射
     * @Author: 翰戈.summer
     * @Date: 2023/11/17
     * @Param: ResourceHandlerRegistry
     * @Return: void
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {

        //处理静态资源无法访问
        ("/**")
                .addResourceLocations("classpath:/static/");
        //处理Swagger无法访问
        ("/")
                .addResourceLocations("classpath:/META-INF/resources/");
        ("/")
                .addResourceLocations("classpath:/META-INF/resources/");
        //处理Swagger的js文件无法访问
        ("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

如果项目中整合了 SpringSecurity6 ,则还需要在 SecurityConfig 配置类中为静态资源放行。

SecurityConfig

import ;
import ;
import ;
import ;
import ;

/**
 * @Description: SpringSecurity配置类
 * @Author: 翰戈.summer
 * @Date: 2023/11/17
 * @Param:
 * @Return:
 */
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    /**
     * 静态资源放行
     */
    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> ().requestMatchers(
                "/",
                "//**",
                "/v3/api-docs",
                "/v3/api-docs/**",
                "/webjars/**",
                "/authenticate",
                "//**",
                "/swagger-resources",
                "/swagger-resources/**"
        );
    }
}

如果不知道如何在 SpringBoot3 项目中整合 SpringSecurity 的话,可以看看我的这篇文章:

/qq_74312711/article/details/134558633?spm=1001.2014.3001.5501

相关文章