SpringBoot2.0整合Swagger2訪問404的解決操作
阿新 • • 發佈:2020-09-29
最近使用最新的SpringBoot2.0整合Swagger2的時候遇到一個問題,整合之後開啟Swagger頁面的時候出現404,後臺提示找不到swagger-ui的頁面。
於是我看了下專案依賴swagger的結構:
可以看到 swagger-ui.html 在META-INF/resources目錄下,所以我們需要手動的將靜態資源路徑指向這裡,在java中配置為:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; 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; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @author xiaqing */ @Configuration @EnableSwagger2 public class SwaggerConfig extends WebMvcConfigurationSupport { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.xqnode.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("介面總覽") .description("測試") .version("1.0") .build(); } /** * 防止@EnableMvc把預設的靜態資源路徑覆蓋了,手動設定的方式 * * @param registry */ @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { // 解決靜態資源無法訪問 registry.addResourceHandler("/**").addResourceLocations("classpath:/static/"); // 解決swagger無法訪問 registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); // 解決swagger的js檔案無法訪問 registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
在swagger的配置類中繼承WebMvcConfigurationSupport,實現addResourceHandlers方法,設定靜態資源可訪問。
設定完成後重啟專案,就可以通過 http://localhost:8080/swagger-ui.html 正常訪問了。
===== 2019.03.13更新 =====
有的同學說配置swagger後靜態資源目錄無法訪問,我自己試了下,確實訪問不了。原來的配置是:
@Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { // 解決swagger無法訪問 registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/").setCachePeriod(0); }
這裡是將所有的請求都指向了META-INF/resources/目錄,顯然是不對的,會導致專案的其他靜態檔案目錄無法正常訪問,於是做了修改:
@Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { // 解決靜態資源無法訪問 registry.addResourceHandler("/**") .addResourceLocations("classpath:/static/"); // 解決swagger無法訪問 registry.addResourceHandler("/swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); // 解決swagger的js檔案無法訪問 registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); }
測試一下:
在resource的static資料夾下新建index.html
啟動專案訪問 http://localhost:8080/index.html
訪問正常,接下來再訪問swagger:
也是正常的。
以上這篇SpringBoot2.0整合Swagger2訪問404的解決操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。