Springboot 集成Swagger

Springboot版本 2.1.14.RELEASE
Swagger版本 2.9.2

1. 引入jar pom.xml中加入

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.9.2</version>
</dependency>
<dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.9.2</version>
</dependency>

2. 加入配置

public class WebConfiguration implements WebMvcConfigurer {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/**").addResourceLocations(
        "classpath:/static/");
    registry.addResourceHandler("/swagger-ui.html").addResourceLocations(
        "classpath:/META-INF/resources/");
    registry.addResourceHandler("/webjars/**").addResourceLocations(
        "classpath:/META-INF/resources/webjars/");
  }
}

3. 如果发现配置了之后仍然无法访问,可以跟踪下源代码 找到正确答案

通过 addResourceHandlers找到父类 org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration#addResourceHandlers
再向上一级 org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport#resourceHandlerMapping

    @Bean
    @Nullable
    public HandlerMapping resourceHandlerMapping() {
        Assert.state(this.applicationContext != null, "No ApplicationContext set");
        Assert.state(this.servletContext != null, "No ServletContext set");

        ResourceHandlerRegistry registry = new ResourceHandlerRegistry(this.applicationContext,
            this.servletContext, mvcContentNegotiationManager(), mvcUrlPathHelper());
        **addResourceHandlers(registry);**

        AbstractHandlerMapping handlerMapping = registry.getHandlerMapping();
        if (handlerMapping == null) {
            return null;
        }
        handlerMapping.setPathMatcher(mvcPathMatcher());
        handlerMapping.setUrlPathHelper(mvcUrlPathHelper());
        handlerMapping.setInterceptors(getInterceptors());
        handlerMapping.setCorsConfigurations(getCorsConfigurations());
        return handlerMapping;
    }      

关键一行代码 addResourceHandlers(registry);

WebMvcConfigurationSupport 有一个空的实现方法
/**
  * Override this method to add resource handlers for serving static resources.
  * @see ResourceHandlerRegistry
*/
protected void addResourceHandlers(ResourceHandlerRegistry registry) {      
}

有人提示 重写该方法,我试了下没有作用。
别人的答案永远只是必然的答案
不过你可以试试,对不对全看运气。

跟踪源码找答案,进步中。。。

posted @ 2020-06-24 11:34  梦见舟  阅读(316)  评论(0编辑  收藏  举报