集成WebMvcConfigurationSupport后,swagger3.0页面404无法访问

1. 问题描述

  • springboot工程,访问服务器静态资源文件,所以添加了配置类继承WebMvcConfigurationSupport
@Slf4j
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {

    @Autowired
    ComponentDirectoryPathReader pathReader;

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        String filePath = "C:\\Users\\Administrator\\Desktop";
        log.info("filePath:"+filePath);
        registry.addResourceHandler("/**").
                addResourceLocations("classpath:/static/").addResourceLocations("classpath:META-INF/resources/").
                addResourceLocations("file:"+filePath);
    }

}
  • 访问swagger页面404

 2.排查思路

查看swagger的配置

  • SwaggerUiWebMvcConfigurer 中配置了swagger静态资源访问路径,所以将其合并到自己的配置类中即可
public class SwaggerUiWebMvcConfigurer implements WebMvcConfigurer {
    private final String baseUrl;

    public SwaggerUiWebMvcConfigurer(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String baseUrl = StringUtils.trimTrailingCharacter(this.baseUrl, '/');
        registry.addResourceHandler(new String[]{baseUrl + "/swagger-ui/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/springfox-swagger-ui/"}).resourceChain(false);
    }

    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController(this.baseUrl + "/swagger-ui/").setViewName("forward:" + this.baseUrl + "/swagger-ui/index.html");
    }
}

3.解决方案

@Slf4j
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {

    @Autowired
    ComponentDirectoryPathReader pathReader;

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        String filePath = "C:\\Users\\Administrator\\Desktop";
        log.info("filePath:"+filePath);
        registry.addResourceHandler("/**").
                addResourceLocations("classpath:/static/").addResourceLocations("classpath:META-INF/resources/").
                addResourceLocations("file:"+filePath);
        registry.addResourceHandler("/swagger-ui/**").addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");

    }

}

 

posted @ 2022-05-07 20:38  heamin-java  阅读(2534)  评论(0编辑  收藏  举报